log4j 2未注销%throwable

cygmwpex  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(266)

我想在使用以下基本log4j log4j2.xml记录错误时打印堆栈跟踪:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="throwable: %throwable"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

这是我的所有依赖项:

<dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.13.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
    </dependencies>

当我运行这个时(asdf不存在):

public class Main {
    public static void main(String[] args) {
        Logger logger = LogManager.getLogger();
        try {
            new FileInputStream("asdf");
        } catch(Exception e) {
            logger.error(e);
        }
    }
}

我的输出是

throwable:

我想要这样的东西:

throwable: java.io.FileNotFoundException: asdf (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at Main.main(Main.java:10)

patternlayout的文档位于:https://logging.apache.org/log4j/2.x/manual/layouts.html#patternlayout 默认(%throwable)应该记录整个堆栈跟踪
任何帮助都太好了!
编辑:我正在使用Java8

cx6n0qe3

cx6n0qe31#

您正在使用 Logger.error(Object) . 具有单个对象参数的所有日志记录方法只记录 toString() 那个东西的价值,即使它是一次性的。在您的例子中,appender模式不包含 %m / %msg / %message 所以您只看到控制台输出中的“throwable:”。
如果我们将消息添加到模式中,则输出为:

throwable: java.io.FileNotFoundException: asdf (The system cannot find the file specified)

在使用log4j2时,这是一个非常常见的陷阱,遗憾的是,这在将来似乎不会改变。
要正确地记录异常及其堆栈跟踪,您可以使用一种带有单独 Throwable 参数,例如。 Logger.error(String, Throwable) ,或者您可以使用 Logger.catching(Level, Throwable) . 但是,应该首选带有消息参数的日志记录方法,因为它们允许您描述上下文。否则,您可能很难找到日志消息的实际创建位置。

相关问题