Java Code Examples for com.dianping.cat.message.Transaction#setStatus()

The following examples show how to use com.dianping.cat.message.Transaction#setStatus() . 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: BaseMessageListener.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void setOnMessageStartTime(ConsumerMessage<T> msg) {
	if (msg instanceof BaseConsumerMessageAware) {
		BaseConsumerMessage<?> baseMsg = ((BaseConsumerMessageAware<?>) msg).getBaseConsumerMessage();
		long now = System.currentTimeMillis();
		baseMsg.setOnMessageStartTimeMills(now);

		Transaction latencyT = null;
		if (!msg.isResend()) {
			latencyT = Cat.newTransaction( //
			      CatConstants.TYPE_MESSAGE_CONSUME_LATENCY, msg.getTopic() + ":" + m_groupId);
		} else {
			latencyT = Cat.newTransaction( //
			      CatConstants.TYPE_MESSAGE_CONSUME_RESEND_LATENCY, msg.getTopic() + ":" + m_groupId);
		}
		long delta = System.currentTimeMillis() - baseMsg.getBornTime();

		if (latencyT instanceof DefaultTransaction) {
			((DefaultTransaction) latencyT).setDurationStart(System.nanoTime() - delta * 1000000L);
		}

		latencyT.addData("key", msg.getRefKey());
		latencyT.setStatus(Transaction.SUCCESS);
		latencyT.complete();
	}
}
 
Example 2
Source File: BrokerLeaseHolder.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, "Broker");
	int count = 0;
	long maxLodedTime = -1L;
	try {
		List<BrokerLease> changes = m_leasesDao.listLatestChanges(new Date(lastRunTime), Networks.forIp()
		      .getLocalHostAddress(), BrokerLeaseEntity.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 3
Source File: AcmeFinancialBackOfficeApplication.java    From cat_lab with MIT License 6 votes vote down vote up
@RequestMapping("/readtimeout")
public String connectionTimeout() throws InterruptedException {
	Transaction t = Cat.newTransaction(CatConstants.TYPE_CALL, "connectionTimeout");
	Thread.sleep(500);
	try {
		log.info("Calling a missing service");
		restTemplate.getForObject("http://localhost:" + MOCK_PORT + "/readtimeout", String.class);
		return "Should blow up";
	} catch(Exception e) {
		t.setStatus(e);
		Cat.getProducer().logError(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example 4
Source File: CatAop.java    From javabase with Apache License 2.0 6 votes vote down vote up
private Object aroundTransaction(String type, String name, ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = null;
    Transaction transaction = null;
    //不让cat异常导致业务异常
    try {
        transaction = Cat.getProducer().newTransaction(type, name);
    } catch (Exception e) {
        log.error("Cat.getProducer().newTransaction Error", e);
    }
    try {
        log.info("大众点评cat拦截:type="+type+";name="+name);
        result = joinPoint.proceed();
        if (transaction != null) transaction.setStatus(Transaction.SUCCESS);
    } catch (Throwable throwable) {
        if (transaction != null) transaction.setStatus(throwable);
        log.error("aroundTransaction exception", throwable);
        throw throwable;
    } finally {
        if (transaction != null)
            transaction.complete();
    }
    return result;
}
 
Example 5
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 6
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void serverSendInFilter(TraceParam traceParam, RpcInvocation invocation) {
    Transaction transaction = (Transaction) traceParam.getAttachment(TRANSACTION);
    if (transaction == null) {
        logger.warn("ServerSide: Request {} won't do cat report, cause no start transaction info.", traceParam.getSpanName());
        return;
    }
    try {
        serverLogEvent(traceParam, invocation);
        transaction.addData(TRACE_ID, traceParam.getTraceId());

        if (traceParam.getThrowable() == null) {
            transaction.setStatus(Transaction.SUCCESS);
        } else {
            Cat.logErrorWithCategory(DORADO_SERVICE + "." + traceParam.getRemoteAppkey(), traceParam.getThrowable());
            transaction.setStatus(traceParam.getThrowable());
        }
    } catch (Exception e) {
        Cat.logErrorWithCategory(DORADO_SERVICE + "." + traceParam.getRemoteAppkey(), e);
        transaction.setStatus(e);
    } finally {
        transaction.complete();
    }
}
 
Example 7
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 8
Source File: ZuulCallable.java    From s2g-zuul with MIT License 5 votes vote down vote up
/**
 * executes "pre" filters
 *
 * @throws ZuulException
 */
private void preRoute() throws ZuulException {
	Transaction tran = Cat.getProducer().newTransaction("ZuulCallable", "preRoute");
	try {
		zuulRunner.preRoute();
		tran.setStatus(Transaction.SUCCESS);
	} catch (Throwable e) {
		tran.setStatus(e);
		throw e;
	} finally {
		tran.complete();
	}
}
 
Example 9
Source File: ConfigSubscriber.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 从zookeeper上获取配置信息
 *
 * @param suffixPath
 *         配置路径
 *
 * @return 配置信息值
 */
@Override
public String getConfigValue(final String suffixPath) {
    final String path = pasePath(suffixPath);
    String data = DynamicPropertyFactory.getInstance().getStringProperty(paseKey(path), null).get();
    if (Check.NuNStr(data)) {
        try {
            if (isExistsNode(path)) {
                data = (String) SerializableSerializer.deserialize(client.getData().forPath(path));
            } else {
                throw new RuntimeException("zk configuration can not find. key:" + path);
            }
            if (!Check.NuNStr(data)) {
                ((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).setOverrideProperty(paseKey(path), data);
            } else {
                throw new RuntimeException("zk configuration value is null. key:" + path);
            }
        } catch (Exception e) {
            logger.error("can't get asura configuration by " + path, e);
            Transaction tran = Cat.newTransaction("get Asura Configuration", path);
            Cat.logError("can't get asura configuration by " + path, e);
            tran.setStatus(e);
            tran.complete();
        }
    }
    return DynamicPropertyFactory.getInstance().getStringProperty(paseKey(path), null).get();
}
 
Example 10
Source File: ZuulCallable.java    From s2g-zuul with MIT License 5 votes vote down vote up
/**
 * executes "post" ZuulFilters
 *
 * @throws ZuulException
 */
private void postRoute() throws ZuulException {
	Transaction tran = Cat.getProducer().newTransaction("ZuulCallable", "postRoute");
	try {
		zuulRunner.postRoute();
		tran.setStatus(Transaction.SUCCESS);
	} catch (Throwable e) {
		tran.setStatus(e);
		throw e;
	} finally {
		tran.complete();
	}
}
 
Example 11
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 12
Source File: CatFilter.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public void initGroupDataSource(GroupDataSource source, JdbcFilter chain) {
	Transaction transaction = Cat.newTransaction(CAT_TYPE, "GroupDataSource.Init-" + source.getJdbcRef());
	try {
		chain.initGroupDataSource(source, chain);
		transaction.setStatus(Message.SUCCESS);
	} catch (RuntimeException e) {
		Cat.logError(e);
		transaction.setStatus(e);
		throw e;
	} finally {
		transaction.complete();
	}
}
 
Example 13
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 14
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 15
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_URL, 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 16
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 17
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 18
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
protected void syncClientRecv(TraceParam traceParam, RpcInvocation invocation) {
    Transaction transaction = (Transaction) traceParam.getAttachment(TRANSACTION);
    if (transaction == null) {
        logger.warn("ClientSide: Request {} won't do cat report, cause no start transaction info.", traceParam.getSpanName());
        return;
    }
    try {
        clientLogEvent(traceParam, invocation);
        if (traceParam.getThrowable() != null) {
            Cat.logErrorWithCategory(DORADO_CALL + "." + traceParam.getRemoteAppkey(), traceParam.getThrowable());
            transaction.setStatus(traceParam.getThrowable());
        } else {
            transaction.setStatus(Transaction.SUCCESS);
        }

        transaction.addData(TRACE_ID, traceParam.getTraceId());
        TraceTimeline timeline = traceParam.getTraceTimeline();
        if (timeline.isEnable()) {
            transaction.addData(CatEventType.INVOKER_PHASECOST.type, timeline.genInvokerAllPhaseCost());
        }
    } catch (Exception e) {
        Cat.logErrorWithCategory(DORADO_CALL + "." + traceParam.getRemoteAppkey(), e);
        transaction.setStatus(e);
    } finally {
        transaction.complete();
    }
}
 
Example 19
Source File: CatFilter.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public void refreshGroupDataSource(GroupDataSource source, String propertiesName, JdbcFilter chain) {
	Transaction t = Cat.newTransaction(CAT_TYPE, "GroupDataSource.Refresh-" + source.getJdbcRef());
	Cat.logEvent("Zebra.Refresh.Property", propertiesName);
	try {
		chain.refreshGroupDataSource(source, propertiesName, chain);
		t.setStatus(Message.SUCCESS);
	} catch (RuntimeException exp) {
		Cat.logError(exp);
		t.setStatus(exp);
		throw exp;
	} finally {
		t.complete();
	}
}
 
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 "";
}