异常和记录器中的不同堆栈跟踪格式

Different stack trace format in exception and logger

如果我使用 exception.printStackTrace() 或如果我使用 logger.error("message", exception),我的异常的堆栈跟踪打印不同。例如,我有例外:

public class TestException extends RuntimeException{

    private int status;

    public TestException(String message, int status) {
        super(message);
        this.status = status;
    }

    public TestException(String message, Throwable cause, int status) {
        super(message, cause);
        this.status = status;
    }

    @Override
    public String toString() {
        return super.toString() + ", status=" + status;
    }
}

如您所见,我已经重写了打印异常状态的 toString 方法。

在 main 方法中我创建了两个 TestException,一个是另一个的原因:

public static void main(String[] args) {
    TestException innerException = new TestException("some inner test", 1);
    TestException exception = new TestException("some text", innerException, 2);

    exception.printStackTrace();
    LOGGER.error(exception.toString(), exception);
}

在 运行 之后,exception.printStackTrace() 打印:

test.App$TestException: some text, status=2
    at test.App.main(App.java:66)
Caused by: test.App$TestException: some inner test, status=1
    at test.App.main(ErrorHandler.java:65)

如您所见,printStackTrace 使用我的异常的 toString 方法并写入异常状态,但 LOGGER.error 打印时没有它:

    11:44:17.153 [main] ERROR test.App - test.App$TestException: some text, status=2
test.App$TestException: some text
    at test.App.main(App.java:66) [classes/:?]
Caused by: test.App$TestException: some inner test
    at test.App.main(App.java:65) ~[classes/:?]

如何配置我的记录器以在打印堆栈跟踪时使用我的异常 toString 方法,与 exception.printStackTrace() 相同?

我正在使用 log4j2,默认 spring boot 2.1.3 配置。

Spring 如果在类路径中找到名为 log4j2.xmllog4j2.jsonlog4j2.yaml 的文件,Boot 会自动配置 Log4j。

您可以使用自己的模式配置文件。您可以在此处找到模式 https://logging.apache.org/log4j/2.x/manual/layouts.html

这是一个示例 log4j2.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="com.example.log4j2demo" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
        </Logger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender" />
        </Root>
    </Loggers>
</Configuration>