Java Code Examples for com.dianping.cat.Cat#newTransaction()

The following examples show how to use com.dianping.cat.Cat#newTransaction() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZuulRequestCommandForSemaphoreIsolation.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
protected HttpResponse run() throws Exception {
	
	Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, httpUriRequest.getURI().toString());
	
    try {
    	HttpResponse response = forward();
        t.setStatus(Transaction.SUCCESS);
        return response;
    } catch (IOException e) {
        t.setStatus(e);
        Cat.logError(e);
    	throw e;
    } finally {
    	t.complete();
    }
}
 
Example 2
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public void initShardDataSource(com.dianping.zebra.shard.jdbc.ShardDataSource source, JdbcFilter chain) {
	String ruleName = source.getRuleName();
	if (StringUtils.isBlank(ruleName)) {
		ruleName = "localMode";
	}

	Transaction transaction = Cat.newTransaction(CAT_TYPE, "ShardDataSource.Init-" + ruleName);

	try {
		chain.initShardDataSource(source, chain);
		transaction.setStatus(Message.SUCCESS);
	} catch (RuntimeException e) {
		Cat.logError(e);
		transaction.setStatus(e);
		throw e;
	} finally {
		transaction.complete();
	}
}
 
Example 3
Source File: CatAopService.java    From piggymetrics with MIT License 6 votes vote down vote up
@Around("@annotation(CatAnnotation)")
public Object aroundMethod(ProceedingJoinPoint pjp) {
	MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
	Method method = joinPointObject.getMethod();

	Transaction t = Cat.newTransaction("method", method.getName());

	try {
		Object obj = pjp.proceed();

		t.setSuccessStatus();
		return obj;
	} catch (Throwable e) {
		t.setStatus(e);
		Cat.logError(e);
		throw new RuntimeException("Exception thrown by CAT aop", e);
	} finally {
		t.complete();
	}
}
 
Example 4
Source File: CatAopService.java    From piggymetrics with MIT License 6 votes vote down vote up
@Around("@annotation(CatAnnotation)")
public Object aroundMethod(ProceedingJoinPoint pjp) {
	MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
	Method method = joinPointObject.getMethod();

	Transaction t = Cat.newTransaction("method", method.getName());

	try {
		Object obj = pjp.proceed();

		t.setSuccessStatus();
		return obj;
	} catch (Throwable e) {
		t.setStatus(e);
		Cat.logError(e);
		throw new RuntimeException("Exception thrown by CAT aop", e);
	} finally {
		t.complete();
	}
}
 
Example 5
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public int executeShardUpdate(ShardStatement source, String sql, int autoGeneratedKeys, int[] columnIndexes,
      String[] columnNames, JdbcFilter chain) throws SQLException {
	SqlAliasManager.setSqlAlias(sql);
	Transaction t = Cat.newTransaction(SHARD_CAT_TYPE, SqlAliasManager.getSqlAlias());
	int result;
	try {
		result = chain.executeShardUpdate(source, sql, autoGeneratedKeys, columnIndexes, columnNames, chain);
		t.setStatus(Message.SUCCESS);
	} catch (Throwable exp) {
		Cat.logError(exp);
		t.setStatus(exp);
		throw new SQLException(exp);
	} finally {
		t.complete();
	}
	return result;
}
 
Example 6
Source File: ConsumerLeaseHolder.java    From hermes with Apache License 2.0 6 votes vote down vote up
private long loadNewLeasesAssignedByOtherMetaservers(long lastRunTime) throws DalException {
	Transaction transaction = Cat.newTransaction(CatConstants.TYPE_LEASE_DIRTY_LOAD, "Consumer");
	int count = 0;
	long maxLodedTime = -1L;
	try {
		List<ConsumerLease> changes = m_leasesDao.listLatestChanges(new Date(lastRunTime), Networks.forIp()
		      .getLocalHostAddress(), ConsumerLeaseEntity.READSET_FULL);
		if (changes != null && !changes.isEmpty()) {
			count = changes.size();
			maxLodedTime = loadExistingLeases(changes);
		}
		transaction.setStatus(Transaction.SUCCESS);
		return maxLodedTime;
	} catch (Exception e) {
		transaction.setStatus(e);
		throw e;
	} finally {
		transaction.addData("count", count);
		transaction.complete();
	}
}
 
Example 7
Source File: DefaultMessageQueueFlusher.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Override
public long flush(int maxMsgCount) {
	long maxPurgedSelectorOffset = purgeExpiredMsgs();
	long maxSavedSelectorOffset = Long.MIN_VALUE;

	int msgCount = 0;

	List<PendingMessageWrapper> todos = new ArrayList<>();
	if (!m_pendingMessages.isEmpty()) {
		PendingMessageWrapper msg = m_pendingMessages.poll();
		todos.add(msg);
		msgCount = msg.getBatch().getMsgSeqs().size();

		PendingMessageWrapper nextMsg = null;
		while ((nextMsg = m_pendingMessages.peek()) != null) {
			int nextPendingMsgCount = nextMsg.getBatch().getMsgSeqs().size();
			if (msgCount + nextPendingMsgCount > maxMsgCount) {
				break;
			}
			todos.add(m_pendingMessages.poll());
			msgCount += nextPendingMsgCount;
		}
	}

	if (!todos.isEmpty()) {
		Transaction catTx = Cat.newTransaction(CatConstants.TYPE_MESSAGE_BROKER_FLUSH, m_topic + "-" + m_partition);
		catTx.addData("count", msgCount);

		maxSavedSelectorOffset = appendMessageSync(todos);

		catTx.setStatus(Transaction.SUCCESS);
		catTx.complete();
	}

	return Math.max(maxPurgedSelectorOffset, maxSavedSelectorOffset);
}
 
Example 8
Source File: CatTransactionMonitor.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public <V> V logTransaction(String type, String name, Callable<V> task) throws Exception {
	Transaction transaction = Cat.newTransaction(type, name);
	try{
		V result = task.call();
		transaction.setStatus(Transaction.SUCCESS);
		return result;
	}catch(Exception th){
		transaction.setStatus(th);
		throw th;
	}finally{
		transaction.complete();
	}
}
 
Example 9
Source File: CatServletFilter.java    From cat_lab with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String url = request.getRequestURL().toString();
    for (String urlPattern : urlPatterns) {
        if (url.startsWith(urlPattern)) {
            url = urlPattern;
        }
    }

    CatContext catContext = new CatContext();
    catContext.addProperty(Cat.Context.ROOT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.PARENT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.CHILD, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID));
    Cat.logRemoteCallServer(catContext);
    
    Transaction t = Cat.newTransaction(CatConstants.TYPE_SERVICE, url);

    try {

        Cat.logEvent("Service.method", request.getMethod(), Message.SUCCESS, request.getRequestURL().toString());
        Cat.logEvent("Service.client", request.getRemoteHost());

        filterChain.doFilter(servletRequest, servletResponse);

        t.setStatus(Transaction.SUCCESS);
    } catch (Exception ex) {
        t.setStatus(ex);
        Cat.logError(ex);
        throw ex;
    } finally {
        t.complete();
    }
}
 
Example 10
Source File: DefaultProducer.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Override
public Future<SendResult> send() {
	Transaction t = null;
	if (m_config.isCatEnabled()) {
		t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_PRODUCE_TRIED, m_msg.getTopic());
	}
	try {
		Topic topic = m_metaService.findTopicByName(m_msg.getTopic());

		if (topic == null) {
			log.error("Topic {} not found.", m_msg.getTopic());
			throw new IllegalArgumentException(String.format("Topic %s not found.", m_msg.getTopic()));
		}

		if (Storage.KAFKA.equals(topic.getStorageType())) {
			m_msg.setWithCatTrace(false);
		}
		m_msg.setBornTime(m_systemClockService.now());
		Future<SendResult> future = m_pipeline.put(m_msg);

		if (t != null) {
			t.setStatus(Transaction.SUCCESS);
		}
		return future;
	} catch (Exception e) {
		if (t != null) {
			Cat.logError(e);
			t.setStatus(e);
		}
		throw e;
	} finally {
		if (t != null) {
			t.complete();
		}
	}
}
 
Example 11
Source File: CatServletFilter.java    From s2g-zuul with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String url = request.getRequestURL().toString();
    for (String urlPattern : urlPatterns) {
        if (url.startsWith(urlPattern)) {
            url = urlPattern;
        }
    }

   Transaction t = Cat.newTransaction("Service", url);

    try {

        PropertyContext propertyContext = new PropertyContext();
        propertyContext.addProperty(Cat.Context.ROOT, request.getHeader(Constants.CAT_ROOT_MESSAGE_ID));
        propertyContext.addProperty(Cat.Context.PARENT, request.getHeader(Constants.CAT_PARENT_MESSAGE_ID));
        propertyContext.addProperty(Cat.Context.CHILD, request.getHeader(Constants.CAT_CHILD_MESSAGE_ID));
        Cat.logRemoteCallServer(propertyContext);

        Cat.logEvent("Service.method", request.getMethod(), Message.SUCCESS, request.getRequestURL().toString());
        Cat.logEvent("Service.client", request.getRemoteHost());

        filterChain.doFilter(servletRequest, servletResponse);

        t.setStatus(Transaction.SUCCESS);
    } catch (Exception ex) {
        t.setStatus(ex);
        Cat.logError(ex);
        throw ex;
    } finally {
        t.complete();
    }
}
 
Example 12
Source File: BrokerMessageSender.java    From hermes with Apache License 2.0 5 votes vote down vote up
private SendMessageCommandV6 createSendMessageCommand(int size) {
	long maxMsgSelectorOffset = Long.MIN_VALUE;
	SendMessageCommandV6 cmd = null;
	List<ProducerWorkerContext> contexts = new ArrayList<ProducerWorkerContext>(size);
	m_queue.drainTo(contexts, size);
	if (!contexts.isEmpty()) {
		cmd = new SendMessageCommandV6(m_topic, m_partition, m_config.getBrokerSenderResultTimeoutMillis());
		for (ProducerWorkerContext context : contexts) {
			int produceTimeoutSeconds = m_config.getProduceTimeoutSeconds(m_topic);

			if (produceTimeoutSeconds > 0
			      && System.currentTimeMillis() - context.m_msg.getBornTime() > produceTimeoutSeconds * 1000) {
				MessageSendException exception = new MessageSendException("Send timeout.", context.m_msg);
				notifySendFail(context.m_future, exception);

				Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_PRODUCE_TIMEOUT, m_topic);
				t.setStatus(Transaction.SUCCESS);
				t.complete();
			} else {
				cmd.addMessage(context.m_msg, context.m_future);
			}
			maxMsgSelectorOffset = Math.max(maxMsgSelectorOffset, context.m_msg.getSelectorOffset());
		}
		cmd.setSelectorOffset(maxMsgSelectorOffset);
		cmd.setTargetIdc(getTargetIdc().toLowerCase());
	}
	return cmd;
}
 
Example 13
Source File: CatTransactionMonitor.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public void logTransactionSwallowException(String type, String name, Task task) {
	
	Transaction transaction = Cat.newTransaction(type, name);
	try{
		task.go();
		transaction.setStatus(Transaction.SUCCESS);
	}catch(Throwable th){
		transaction.setStatus(th);
		logger.error("[logTransaction]" + type + "," + name + "," + task, th);
	}finally{
		transaction.complete();
	}
}
 
Example 14
Source File: ConfigSubscriber.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化zk连接
 *
 * @author zhangshaobin
 * @created 2013-6-26 上午10:21:34
 */
private void init() {
    applicationName = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.CONFIG_APPLICATION_NAME_KEY, null).get();
    String zkConfigEnsemble = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.ZK_ENSEMABLE_KEY, null).get();
    Integer zkConfigSessionTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_SESSION_TIMEOUT_KEY, 15000).get();
    Integer zkConfigConnTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_CONN_TIMEOUT_KEY, 5000).get();

    Transaction tran = Cat.newTransaction("Asura Configuration init", applicationName + "_" + zkConfigEnsemble);

    try {

        if (Check.NuNStr(zkConfigEnsemble)) {
            logger.warn("ZooKeeper configuration running in file mode, zk is not enabled since not configured");
            Cat.logError("zk is not enabled since not configured", new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started."));
            return;
        }

        client = createAndStartZKClient(zkConfigEnsemble, zkConfigSessionTimeout, zkConfigConnTimeout);

        if (client.getState() != CuratorFrameworkState.STARTED) {
            throw new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started.");
        }

        tran.setStatus(Transaction.SUCCESS);
    } catch (Exception e) {
        logger.error("连接配置中心服务器超时,时间5000毫秒。", e);
        Cat.logError("asura configuration init exception", e);
        tran.setStatus(e);
        System.exit(1);
    } finally {
        tran.complete();
    }
    logger.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date()) + applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
    logger.info(applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
}
 
Example 15
Source File: DefaultSendMessageResultMonitor.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void tracking(SendMessageCommandV6 sendMessageCommand) {
	if (m_config.isCatEnabled()) {
		Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_PRODUCE_ACKED, sendMessageCommand.getTopic());
		for (List<ProducerMessage<?>> msgs : sendMessageCommand.getProducerMessages()) {
			for (ProducerMessage<?> msg : msgs) {
				MessageTree tree = Cat.getManager().getThreadLocalMessageTree();

				String msgId = msg.getDurableSysProperty(CatConstants.SERVER_MESSAGE_ID);
				String parentMsgId = msg.getDurableSysProperty(CatConstants.CURRENT_MESSAGE_ID);
				String rootMsgId = msg.getDurableSysProperty(CatConstants.ROOT_MESSAGE_ID);

				tree.setMessageId(msgId);
				tree.setParentMessageId(parentMsgId);
				tree.setRootMessageId(rootMsgId);

				long duration = System.currentTimeMillis() - msg.getBornTime();
				String type = duration > 2000L ? CatConstants.TYPE_MESSAGE_PRODUCE_ELAPSE_LARGE
				      : CatConstants.TYPE_MESSAGE_PRODUCE_ELAPSE;
				CatUtil.logElapse(type, msg.getTopic(), msg.getBornTime(), 1,
				      Arrays.asList(new Pair<String, String>("key", msg.getKey())), Transaction.SUCCESS);
				ProducerStatusMonitor.INSTANCE.sendSuccess(msg.getTopic(), msg.getPartition(), duration);
			}
		}
		t.addData("*count", sendMessageCommand.getMessageCount());
		t.setStatus(Transaction.SUCCESS);
		t.complete();
	}
}
 
Example 16
Source File: CatServletFilter.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String url = request.getRequestURL().toString();
    for (String urlPattern : urlPatterns) {
        if (url.startsWith(urlPattern)) {
            url = urlPattern;
        }
    }

    CatContext catContext = new CatContext();
    catContext.addProperty(Cat.Context.ROOT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.PARENT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.CHILD, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID));
    Cat.logRemoteCallServer(catContext);
    
    Transaction t = Cat.newTransaction("Service", url);

    try {

        Cat.logEvent("Service.method", request.getMethod(), Message.SUCCESS, request.getRequestURL().toString());
        Cat.logEvent("Service.client", request.getRemoteHost());

        filterChain.doFilter(servletRequest, servletResponse);

        t.setStatus(Transaction.SUCCESS);
    } catch (Exception ex) {
        t.setStatus(ex);
        Cat.logError(ex);
        throw ex;
    } finally {
        t.complete();
    }
}
 
Example 17
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void serverRecv(TraceParam traceParam, RpcInvocation invocation) {
    if (TraceTimeline.isEnable(invocation)) {
        // do nothing, 在serveSend中通过newTransactionWithDuration上报耗时
    } else {
        Transaction transaction = Cat.newTransaction(DORADO_SERVICE, traceParam.getSpanName());
        traceParam.putAttachment(TRANSACTION, transaction);
    }
}
 
Example 18
Source File: BaseMessageListener.java    From hermes with Apache License 2.0 4 votes vote down vote up
@Override
public void onMessage(List<ConsumerMessage<T>> msgs) {
	if (msgs != null && !msgs.isEmpty()) {
		String topic = msgs.get(0).getTopic();

		for (ConsumerMessage<T> msg : msgs) {
			Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_CONSUMED, topic + ":" + m_groupId);
			MessageTree tree = Cat.getManager().getThreadLocalMessageTree();

			if (msg instanceof PropertiesHolderAware) {
				PropertiesHolder holder = ((PropertiesHolderAware) msg).getPropertiesHolder();
				String rootMsgId = holder.getDurableSysProperty(CatConstants.ROOT_MESSAGE_ID);
				String parentMsgId = holder.getDurableSysProperty(CatConstants.CURRENT_MESSAGE_ID);

				tree.setRootMessageId(rootMsgId);
				tree.setParentMessageId(parentMsgId);
			}

			try {
				t.addData("topic", topic);
				t.addData("key", msg.getRefKey());
				t.addData("groupId", m_groupId);

				setOnMessageStartTime(msg);
				onMessage(msg);
				setOnMessageEndTime(msg);
				// by design, if nacked, no effect
				msg.ack();

				String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
				Cat.logEvent("Consumer:" + ip, msg.getTopic() + ":" + m_groupId, Event.SUCCESS, "key=" + msg.getRefKey());
				Cat.logEvent("Message:" + topic, "Consumed:" + ip, Event.SUCCESS, "key=" + msg.getRefKey());
				Cat.logMetricForCount(msg.getTopic());
				t.setStatus(MessageStatus.SUCCESS.equals(msg.getStatus()) ? Transaction.SUCCESS : "FAILED-WILL-RETRY");
			} catch (Exception e) {
				Cat.logError(e);
				t.setStatus(e);
				log.error("Exception occurred while calling onMessage.", e);
				msg.nack();
			} finally {
				t.complete();
			}
		}

	}
}
 
Example 19
Source File: CatTest.java    From x-pipe with Apache License 2.0 4 votes vote down vote up
@Test
public void testEnable() {
	Cat.newTransaction("test", "test");
}
 
Example 20
Source File: CatController.java    From javabase with Apache License 2.0 3 votes vote down vote up
/**
 * Transaction
 a).transaction适合记录跨越系统边界的程序访问行为,比如远程调用,数据库调用,也适合执行时间较长的业务逻辑监控
 b).某些运行期单元要花费一定时间完成工作, 内部需要其他处理逻辑协助, 我们定义为Transaction.
 c).Transaction可以嵌套(如http请求过程中嵌套了sql处理).
 d).大部分的Transaction可能会失败, 因此需要一个结果状态码.
 e).如果Transaction开始和结束之间没有其他消息产生, 那它就是Atomic Transaction(合并了起始标记).
 Event
 a). Event用来记录次数,表名单位时间内消息发生次数,比如记录系统异常,它和transaction相比缺少了时间的统计,开销比transaction要小
 
 type和name的组合要满足全局唯一性
    Transaction type有 "URL", "SQL", "Email", "Exec"等
    Event type有 "Info", "Warn", "Error"
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/transation", method = RequestMethod.GET)
public String transation() throws Exception {
	// Transaction的type
	Transaction t = Cat.newTransaction("TransactionTest", "findorder");
	// 3.Event Event用来记录次数,表名单位时间内消息发生次数,比如记录系统异常,它和transaction相比缺少了时间的统计,开销比transaction要小
	Cat.logEvent("info", "transation", Message.SUCCESS, "参数1");
	Cat.logEvent("error", "transation", Message.SUCCESS, "参数1");
	t.addData("Transaction测试");
	t.setStatus(Message.SUCCESS);
	t.complete();
	return "";
}