CAT是美团开源的一款比较好的业务性能监控的工具,CatClient会异步的将信息上报到CAT服务端,服务端可以将数据集成到ES然后使用Kibana做视图的渲染,为了防止某些重要的ERROR错误漏掉,我们可以自定义一个CatAppender,代码如下
public class CatAppender extends AppenderBase<ILoggingEvent> {
@Override
protected void append(ILoggingEvent event) {
try {
boolean isTraceMode = Cat.getManager().isTraceMode();
Level level = event.getLevel();
if (level.isGreaterOrEqual(Level.ERROR)) {
logError(event);
} else if (isTraceMode) {
logTrace(event);
}
} catch (Exception ex) {
throw new LogbackException(event.getFormattedMessage(), ex);
}
}
private void logError(ILoggingEvent event) {
ThrowableProxy info = (ThrowableProxy) event.getThrowableProxy();
if (info != null) {
Throwable exception = info.getThrowable();
String message = event.getFormattedMessage();
if (message != null ) {
//调用cat记录相关的错误信息
Cat.logError( String.valueOf(message), exception);
} else {
Cat.logError(exception);
}
}
}
private void logTrace(ILoggingEvent event) {
String type = "Logback";
String name = event.getLevel().toString();
Object message = event.getFormattedMessage();
String data;
if (message instanceof Throwable) {
data = buildExceptionStack((Throwable) message);
} else {
data = event.getFormattedMessage().toString();
}
ThrowableProxy info = (ThrowableProxy) event.getThrowableProxy();
if (info != null) {
data = data + '\n' + buildExceptionStack(info.getThrowable());
}
TitansCat.getInstance().logTrace(type, name, "0", data);
}
private String buildExceptionStack(Throwable exception) {
if (exception != null) {
StringWriter writer = new StringWriter(2048);
exception.printStackTrace(new PrintWriter(writer));
return writer.toString();
} else {
return "";
}
}
}
在xml配置中,只需要root ref这个Appender即可,如下
<root level="info">
<appender-ref ref="consoleWithSwitch"/>
<appender-ref ref="catAppender"/>
<appender-ref ref="file"/>
</root>
注意,虽然说我们定义了一个catAppender,但是大部分的性能的采集还是靠catClient和自定义的埋点来实现。
后面的系列文章,会分析下整个CAT的架构和源码分析,如果logging模块还有新的内容,会进行追加。
网友评论