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

The following examples show how to use com.dianping.cat.Cat#logEvent() . 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: SendMessageCommandProcessorV3.java    From hermes with Apache License 2.0 6 votes vote down vote up
private boolean isRateLimitExceeded(String topic, int partition, int msgCount, int bytes) {
	RateLimiter qpsRateLimiter = m_config.getPartitionProduceQPSRateLimiter(topic, partition);
	RateLimiter bytesRateLimiter = m_config.getPartitionProduceBytesRateLimiter(topic, partition);
	if (qpsRateLimiter.tryAcquire(msgCount)) {
		if (bytesRateLimiter.tryAcquire(bytes)) {
			return false;
		} else {
			Cat.logEvent(CatConstants.TYPE_MESSAGE_BROKER_BYTES_RATE_LIMIT_EXCEED, topic + "-" + partition,
			      Event.SUCCESS, "msgCount=" + msgCount + "&bytes=" + bytes);
		}
	} else {
		Cat.logEvent(CatConstants.TYPE_MESSAGE_BROKER_QPS_RATE_LIMIT_EXCEED, topic + "-" + partition, Event.SUCCESS,
		      "msgCount=" + msgCount + "&bytes=" + bytes);
	}

	return true;
}
 
Example 2
Source File: ReadOnlyEchoClientHandler.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if(!(msg instanceof String)) {
        Cat.logEvent("UNEXPECTED.TYPE", msg.getClass().getName());
    }
    if (!message.equals(msg)) {
        Cat.logEvent("Not.Equals", (String) msg);
        logger.info("[not equals][receive]{}", msg);
        logger.info("[not equals][expect]{}", message);
        System.out.println("[not equal]");
    }
    logger.debug("SEND.OUT: {}", message);
}
 
Example 3
Source File: CatUtil.java    From hermes with Apache License 2.0 5 votes vote down vote up
public static void logEventPeriodically(String type, String name, long count) {
	Pair<AtomicLong, AtomicLong> countAndLastLogTimePair = m_catEventLastLogTimes
	      .getUnchecked(new Pair<>(type, name));
	long now = System.currentTimeMillis();

	if (now - countAndLastLogTimePair.getValue().get() >= 20000) {
		countAndLastLogTimePair.getValue().set(now);
		Cat.logEvent(type, name, Event.SUCCESS, "*count=" + countAndLastLogTimePair.getKey().getAndSet(0));
	} else {
		countAndLastLogTimePair.getKey().addAndGet(count);
	}
}
 
Example 4
Source File: SendMessageCommandProcessorV6.java    From hermes with Apache License 2.0 5 votes vote down vote up
private boolean isRateLimitExceeded(String topic, int partition, int msgCount, int bytes) {
	RateLimiter qpsRateLimiter = m_config.getPartitionProduceQPSRateLimiter(topic, partition);
	RateLimiter bytesRateLimiter = m_config.getPartitionProduceBytesRateLimiter(topic, partition);
	if (qpsRateLimiter.tryAcquire(msgCount)) {
		if (bytesRateLimiter.tryAcquire(bytes)) {
			return false;
		} else {
			Cat.logEvent(CatConstants.TYPE_MESSAGE_BROKER_BYTES_RATE_LIMIT_EXCEED, topic + "-" + partition);
		}
	} else {
		Cat.logEvent(CatConstants.TYPE_MESSAGE_BROKER_QPS_RATE_LIMIT_EXCEED, topic + "-" + partition);
	}

	return true;
}
 
Example 5
Source File: ClusterStateHolder.java    From hermes with Apache License 2.0 5 votes vote down vote up
public void becomeObserver() {
	m_roleLock.writeLock().lock();
	try {
		log.info("Become Observer!!!");
		Cat.logEvent(CatConstants.TYPE_ROLE_CHANGED, "Observer");
		m_role = Role.OBSERVER;
		long newVersion = m_guard.upgradeVersion();
		closeLeaderLatch();
		m_eventBus.pubEvent(new Event(EventType.OBSERVER_INIT, newVersion, null));
	} finally {
		m_roleLock.writeLock().unlock();
	}
}
 
Example 6
Source File: CatFilter.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public void shardRouting(RouterResult rr, JdbcFilter chain) throws SQLException {
	if (rr != null) {
		if (rr.getSqls() != null) {
			for (RouterResult.RouterTarget routerTarget : rr.getSqls()) {
				Cat.logEvent("ShardSQL.Route", routerTarget.getDatabaseName(), Message.SUCCESS,
				      String.valueOf(routerTarget.getSqls().size()));
			}
		} else if (rr.getParams() != null) {
			Cat.logEvent("ShardSQL.Route", null, "Invalid Params", Stringizers.forJson().compact()
			      .from(rr.getParams()));
		}
	}
	chain.shardRouting(rr, chain);
}
 
Example 7
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 8
Source File: RabbitMqSendClient.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 发送消息-topic方式
 *
 * @param exchangeName 格式为:系统标示_模块标示_功能标示
 * @param msg          具体消息
 * @author zhangshaobin
 * @created 2016年3月1日 下午4:40:59
 */
public void sendTopic(ExchangeName exchangeName, RoutingKey routingKey, PublishSubscribeType type, String msg) throws Exception {
    initTopicChannel();
    String _exchange = exchangeName.getNameByEnvironment(environment);
    Transaction trans = Cat.newTransaction("RabbitMQ Message", "PUBLISH-TOPIC-" + _exchange);
    RabbitMessage rm = new RabbitMessage();
    rm.setData(msg);
    rm.setType(_exchange);
    try {
        Cat.logEvent("mq send topic",exchangeName.getName(),Event.SUCCESS, rm.toJsonStr());
        rm.setType(_exchange);
        topicChannel.exchangeDeclare(_exchange, type.getName(), true);
        topicChannel.basicPublish(_exchange, routingKey.getKey(), null, rm.toJsonStr().getBytes("UTF-8"));
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("SEND SUCCESS:[queue:{},message:{}]", _exchange, rm.toJsonStr());
        }
        Cat.logMetricForCount("PUBLISH-TOPIC-" + _exchange); // 统计请求次数, 可以查看对应队列中放入了多少信息
        trans.setStatus(Transaction.SUCCESS);
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("SEND ERROR:[queue:{},message:{},exception:{}]", _exchange, rm.toJsonStr(), e);
        }
        String err = exchangeName + "  rabbitmq发送消息异常";
        Cat.logError(err, e);
        trans.setStatus(e);
        throw new AsuraRabbitMqException(err, e);
    } finally {
        trans.complete();
    }
}
 
Example 9
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 10
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
private void clientLogEvent(TraceParam traceParam, RpcInvocation invocation) {
    Cat.logEvent(CatEventType.INVOKER_SERVER_APPKEY.getType(), traceParam.getRemoteAppkey());
    Cat.logEvent(CatEventType.INVOKER_SERVER_IP.getType(), traceParam.getRemoteIp());
    Cat.logEvent(CatEventType.INVOKER_TIMEOUT.getType(), String.valueOf(traceParam.getTimeout()));
    Cat.logEvent(CatEventType.INVOKER_CALL_TYPE.getType(), AsyncContext.isAsyncReq(invocation) ? "Async" : "Sync");
    Cat.logEvent(CatEventType.INVOKER_PROTOCOL_TYPE.getType(), traceParam.getProtocol());
    Cat.logEvent(CatEventType.INVOKER_REQUEST_SIZE.getType(), SizeUtil.getLogSize(traceParam.getRequestSize()));
    Cat.logEvent(CatEventType.INVOKER_RESPONSE_SIZE.getType(), SizeUtil.getLogSize(traceParam.getResponseSize()));
}
 
Example 11
Source File: CatFilter.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource initSingleDataSource(SingleDataSource source, JdbcFilter chain) {
	DataSource result = chain.initSingleDataSource(source, chain);
	SingleDataSourceMonitor monitor = new SingleDataSourceMonitor(source);
	this.monitors.put(source, monitor);
	try {
		StatusExtensionRegister.getInstance().register(monitor);
	} catch (Throwable ignore) {
	}
	Cat.logEvent("SingleDataSource.Created", source.getConfig().getJdbcUrl());
	Cat.logEvent("SingleDataSource.Type", source.getConfig().getType());
	return result;
}
 
Example 12
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 13
Source File: EchoClientStarter.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private static void doConnect(String host, int port, String protocol, int speed) {
    AdvancedEchoClient client = new AdvancedEchoClient(host, port, protocol, speed);

    Cat.logEvent("Start", System.nanoTime()+"");
    try {
        client.startServer().channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
        logger.error("[doConnect]", e);
        Cat.logError("ReConnected", e);
    } finally {
        scheduled.schedule(()->doConnect(host, port, protocol, speed), 1, TimeUnit.MINUTES);
    }

}
 
Example 14
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 15
Source File: MySQLMessageQueueStorage.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void logSelecotrMetric(String topic, int partition, boolean priority, int count) {
	TreeMap<Integer, String> metricNames = priority ? m_catSelectorByPriorityMetrics
	      : m_catSelectorByNonPriorityMetrics;

	Entry<Integer, String> ceilingEntry = metricNames.ceilingEntry(count);

	Cat.logEvent(ceilingEntry.getValue(), topic + "-" + partition);
}
 
Example 16
Source File: MobileExecuteRoute.java    From s2g-zuul with MIT License 4 votes vote down vote up
@Override
public Object run() throws ZuulException {
	Transaction tran = Cat.getProducer().newTransaction("Filter", "ExecuteRoute");
	RequestContext ctx = RequestContext.getCurrentContext();
	HttpServletRequest request = ctx.getRequest();
	String url = ctx.getRouteUrl().toString();
	String groupName = null;
	String routeName = null;

	try {
		Cat.logEvent("route.url", url);
		HttpClient httpclient = clientRef.get();
		Collection<Header> headers = buildZuulRequestHeaders(request);
		InputStream requestEntity = getRequestBody(request);
		int contentLength = request.getContentLength();
		groupName = ctx.getRouteGroup();
		routeName = ctx.getRouteName();

		if (groupName == null)
			groupName = Constants.DEFAULT_GROUP;
		if (routeName == null)
			routeName = Constants.DEFAULT_NAME;
		RequestConfig requestConfig = buildRequestConfig(routeName, groupName);
		String verb = request.getMethod().toUpperCase();

		HttpResponse response = forward(httpclient, requestConfig, verb, url, headers, requestEntity, contentLength,
				groupName, routeName);
		setResponse(response);
		tran.setStatus(Transaction.SUCCESS);

	} catch (Exception e) {
		tran.setStatus(e);
		String originUrl = getOriginatingURL();
		String targetUrl = url;
		String targetIp = "unknown";
		try {
			targetIp = InetAddress.getByName(ctx.getRouteUrl().getHost()).getHostAddress();
		} catch (Exception ignore) { }

		Exception ex = e;
		//String errorMsg =String.format("[${ex.class.simpleName}]{${ex.message}}   ");
		String errorMsg =String.format("[%s]{%s}   ",ex.getClass().getSimpleName(),ex.getMessage());
		Throwable cause = null;
		while ((cause = ex.getCause()) != null) {
			ex = (Exception) cause;
			//errorMsg = "${errorMsg}[${ex.class.simpleName}]{${ex.message}}   ";
			errorMsg += String.format("[%s]{%s}   ",ex.getClass().getSimpleName(),ex.getMessage());
		}

		//Cat.logError("Service Execution Error,OriginUrl: ${originUrl}\nTargetUrl: ${targetUrl}\nTargetIp: ${targetIp}\nCause: ${errorMsg}", e);
		Cat.logError(String.format("Service Execution Error,OriginUrl: %s\nTargetUrl: %s\nTargetIp: %s\nCause: %s\n,groupName:%s\n,routeName:%s",originUrl,targetUrl,targetIp,errorMsg,groupName,routeName), e);
		//throw new ZuulException(errorMsg,500, "TargetUrl: ${targetUrl}\nCause: ${errorMsg}");
		throw new ZuulException(errorMsg,500, String.format("TargetUrl: %s\nCause: %s",targetUrl,errorMsg));
	} finally {
		tran.complete();
	}

	return null;
}
 
Example 17
Source File: SystemLogger.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
@Around("execution(* com..*.proxy..*.* (..))")
public Object doBasicProfiling(final ProceedingJoinPoint joinPoint) throws Throwable {
	long start_all = System.currentTimeMillis();
	long end_all = 0L;
	String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
	String signatureName = joinPoint.getSignature().getName();
	Object [] args = joinPoint.getArgs();
	Transaction tran = Cat.newTransaction("Aspect-proxy", declaringTypeName + "." + signatureName);
	if (RpcContext.getContext().getRemoteAddressString() != null && RpcContext.getContext().getMethodName() != null
			&& RpcContext.getContext().getUrl() != null) {
		MDC.put(HOST, RpcContext.getContext().getRemoteAddressString());
		MDC.put(INTERFACE, RpcContext.getContext().getUrl().getServiceInterface());
		MDC.put(METHOD, RpcContext.getContext().getMethodName());
	} else {
		MDC.put(HOST, "127.0.0.1");
		MDC.put(INTERFACE, "none");
		MDC.put(METHOD, "none");
	}

	final DataLogEntity de = new DataLogEntity();
	de.setClassName(declaringTypeName);
	de.setMethodName(signatureName);
	de.setParams(args);
	String logJson = de.toJsonStr();
	// 参数日志
	if (logger.isDebugEnabled()) {
		logger.debug(de.toJsonStr());
	}
	try {
		long start = System.currentTimeMillis();
		final Object retVal = joinPoint.proceed();
		long end = System.currentTimeMillis();
		// 记录耗时
		logger.info("{}, 耗时:{} ms, 进入aop到执行完耗时:{} ms", logJson, (end - start), (end - start_all));
		Cat.logEvent(declaringTypeName, signatureName, "0", logJson+" 耗时:" + (end - start) + " ms" + " 时间戳:" + System.currentTimeMillis());
		/**
		 * 设置消息的状态,必须设置,0:标识成功,其他标识发生了异常
		 */
		tran.setStatus(Transaction.SUCCESS);
		end_all = System.currentTimeMillis();
		return retVal;
	} catch (final Exception e) {
		final ErrorLogEntity ele = new ErrorLogEntity(de);
		DataTransferObject dto = handleException(e, ele, tran);
		end_all = System.currentTimeMillis();
		// 方法返回值类型
		Class returnType = null;
		if (null != joinPoint.getSignature()) {
			returnType = ((MethodSignature) joinPoint.getSignature()).getReturnType();
		}
		if (null != returnType && returnType.equals(String.class)){
			return dto.toJsonString();
		}else if (null != returnType && returnType.equals(DataTransferObject.class)){
			return dto;
		}else{
			throw e;
		}
	} finally {
		MDC.remove(HOST);
		MDC.remove(INTERFACE);
		MDC.remove(METHOD);
		tran.complete();
		logger.info("{}, 接入cat后整体耗时: {} ms", logJson, (end_all - start_all));
	}
}
 
Example 18
Source File: CatFilter.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@Override
public void shardMerge(ShardResultSet rs, JdbcFilter chain) throws SQLException {
	Cat.logEvent("ShardSQL.Merge", "Begin");
	chain.shardMerge(rs, chain);
}
 
Example 19
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 20
Source File: CatFilter.java    From Zebra with Apache License 2.0 4 votes vote down vote up
private void logSqlDatabaseEvent(SingleConnection conn, String status) throws SQLException {
	SingleConnection singleConnection = conn instanceof SingleConnection ? (SingleConnection) conn : null;
	if (singleConnection != null && conn.getMetaData() != null) {
		Cat.logEvent("SQL.Database", conn.getMetaData().getURL(), status, singleConnection.getDataSourceId());
	}
}