如何为多行日志输出添加缩进

db2dz4w8  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(514)

我不认为,我是第一个想要这个,但我找不到它的配置。
典型的logback日志输出如下所示:

2021-01-07 13:26:04,639 [MyThread] ERROR [] one.of.my.Classes - Some nice error message : java.lang.RuntimeException
java.lang.RuntimeException: null
    at one.of.my.Classes.method0(Classes:123)
    at one.of.my.Classes.method2(Classes:33)
    ...
Caused by: foo.bar.AnotherException: Blah
    at one.of.my.other.Clazz(Foo.java:693)
    ...
2021-01-07 13:26:04,639 [MyThread]  INFO [] one.of.my.Classes - Multi line info message
Second line
Third line
2021-01-07 13:26:04,639 [MyThread]  INFO [] Some other output

为了使输出更易于阅读,也更易于日志解析器处理,我想为属于另一行的行添加缩进,例如:

2021-01-07 13:26:04,639 [MyThread] ERROR [] one.of.my.Classes - Some nice error message : java.lang.RuntimeException
    java.lang.RuntimeException: null
        at one.of.my.Classes.method0(Classes:123)
        at one.of.my.Classes.method2(Classes:33)
        ...
    Caused by: foo.bar.AnotherException: Blah
        at one.of.my.other.Clazz(Foo.java:693)
        ...
2021-01-07 13:26:04,639 [MyThread]  INFO [] one.of.my.Classes - Multi line info message
    Second line
    Third line
2021-01-07 13:26:04,639 [MyThread]  INFO [] Some other output

那么,如何使用logback实现这一点呢?

klr1opcd

klr1opcd1#

您可以为记录器实现自己的自定义布局。
布局是负责将传入事件转换为字符串的logback组件。
如何处理日志消息由您决定。简单示例:

public class MyLayout extends LayoutBase<ILoggingEvent> {

    @Override
    public String doLayout(ILoggingEvent event) {
        StringBuffer sbuf = new StringBuffer(128);
        sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime());
        sbuf.append(" ");
        sbuf.append(event.getLevel());
        sbuf.append(event.getLoggerName());
        sbuf.append(" - ");
        //few indentations for a new line
        sbuf.append(event.getFormattedMessage().replaceAll("\n", "\n  ")); 
        sbuf.append(CoreConstants.LINE_SEPARATOR);
        return sbuf.toString();
    }
}

logback.xml文件

<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="com.log.test.layout.MyLayout" />
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>

相关问题