我使用logback和slf4j登录Spring Boot应用程序。我创建了一个自定义的布局类,因为所有的日志语句都被包装为一个json。我已经配置了如下所示的logback-spring.xml以采用自定义布局。有用!Logback - logback.xml中的布局和模式
问题是我无法应用该模式。只有布局可以工作(或)模式。我想要的是始终在日志中,转到布局类,然后在记录之前应用模式。
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${user.home}/logs/sample.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.home}/logs/sample_%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- how many days to keep the files -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.test.test.payment.core.logging.SampleLogLayout" >
</layout>
</encoder>
*<!-- <encoder>
<charset>UTF-8</charset>
<Pattern>{"@timestamp": "%d{yyyy-MM-dd HH:mm:ss.SSS}", "priority": "%p", "application": "payment",
"class": "%C", "file": "%F:%L", "payload": %m }%n
</Pattern>
</encoder>-->*
</appender>
这里的SampleLogLayout
类:
public class SampleLogLayout extends LayoutBase<LoggingEvent> {
@Override
public String doLayout(LoggingEvent event) {
String renderedMessage = event.getMessage();
if (!isJson(renderedMessage)) {
Throwable throwable = null;
if (event.getLevel().equals(Level.ERROR) || event.getLevel().equals(Level.WARN)) {
final IThrowableProxy throwableProxy = event.getThrowableProxy();
if ((throwableProxy != null) && (throwableProxy instanceof ThrowableProxy)) {
ThrowableProxy proxy = (ThrowableProxy) throwableProxy;
throwable = proxy.getThrowable();
}
String message = LogErrorMessage.create(CommonCoreErrors.GENERIC_ERROR)
.message(renderedMessage).exception(throwable).build();
return message;
} else {
return LogMessage.create(renderedMessage).build();
}
}
return renderedMessage;
}
private boolean isJson(String msg) {
if (null == msg) {
return false;
} else {
return msg.startsWith("{") && msg.endsWith("}");
}
}
}
我认为,我们需要看到这个类太:'com.test.test.payment.core.logging.SampleLogLayout' – glytching
是的,增加了我的SampleLogLayout类。基本上LogErrorMessage.create()和LogMessage.create()将消息转换为JSON – deejo
好的,这很有用。我仍然不清楚问题是什么。你是说你想'SampleLogLayout'发出带有模式的'renderedMessage'?也许增加(1)一个示例日志调用(以便我们可以看到'renderedMessage'看起来像什么)和(2)期望的输出将有助于澄清事情。 – glytching