问题描述
我们正在将日志从文本"更改为JSON.我使用以下代码实现JSON日志:
We are changing our logs from Text to JSON. I used below code to implement JSON logs :
LayoutWrappingEncoder layoutEncoder = new LayoutWrappingEncoder();
ch.qos.logback.contrib.json.classic.JsonLayout layout= new ch.qos.logback.contrib.json.classic.JsonLayout();
ch.qos.logback.contrib.jackson.JacksonJsonFormatter jsonFormatter=new ch.qos.logback.contrib.jackson.JacksonJsonFormatter();
jsonFormatter.setPrettyPrint(true);
layout.setJsonFormatter(jsonFormatter);
layout.setTimestampFormat("yyyy-MM-dd' 'HH:mm:ss.SSS");
layoutEncoder.setLayout(layout);
但是我看到JSON日志没有完全打印出来.
But I see that JSON logs are not printed entirely.
{
"timestamp" : "2019-08-22 10:12:15.790",
"level" : "ERROR",
"thread" : "qtp1346354118-22",
"logger" :"com.SomeClass",
"message" : "Exception from : com.class.method() \n",
"context" : "default",
"exception" : "java.lang.NullPointerException: null\r\n"
}
现在,不使用完整的堆栈跟踪打印异常,就像它们如何在文本日志中获取日志一样.我还可以看到打印了新的换行符序列,这在文本日志中也不会发生.
Now, the exception are not printed with complete stack trace, like how they use to get logs in text logs. Also I could see new line escape sequence getting printed which also does not happen in text logs.
我尝试探索JSONLayout中的一些属性,但没有一个解决了我的问题.
I tried exploring some properties in JSONLayout but none of them solved my problem.
那么我还能在这里尝试
推荐答案
按如下所示定义CustomThrowableProxyConverter并将其设置到您的JsonLayout中.它可以解决问题.
Define a CustomThrowableProxyConverter as follows and set it into your JsonLayout. It does the trick.
CustomThrowableProxyConverter extends ThrowableHandlingConverter {
public CustomThrowableProxyConverter() {
}
@Override
public String convert(ILoggingEvent event) {
StringBuilder sb = new StringBuilder();
IThrowableProxy itp = event.getThrowableProxy();
if (itp instanceof ThrowableProxy) {
ThrowableProxy tp = (ThrowableProxy)itp;
sb.append(tp.getClassName() + ": " + tp.getMessage());
for (StackTraceElementProxy element : tp.getStackTraceElementProxyArray()) {
sb.append("\t\n");
sb.append(element.getSTEAsString());
}
return sb.toString();
}
return "";
}
}
然后将其设置为jsonLayout实例.
Then set this into jsonLayout instance.
JsonLayout jsonLayout = new JsonLayout();
jsonLayout.setThrowableProxyConverter(new CustomThrowableProxyConverter());
jsonEncoder.setLayout(jsonLayout);
这篇关于LOGBACK:如何使用JSONLayout记录整个味精的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!