带有Log4j的Slf4j在包装异常有消息时不打印包装的异常(由)。[英] Slf4j with Log4j does not print wrapped exception (caused by) when wrapper exception has a message

本文是小编为大家收集整理的关于带有Log4j的Slf4j在包装异常有消息时不打印包装的异常(由)。的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

第一个例子:

public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws Exception {
        try {
            throw new RuntimeException(new NullPointerException("NPE"));
        } catch (RuntimeException e) {
            logger.error("Error:", e);
        }
    }
}

输出:

Error:
java.lang.RuntimeException: java.lang.NullPointerException: NPE
    at Main.main(Main.java:10)

在第二个例子中,我们也只是向 RuntimeException 添加了一条消息:

throw new RuntimeException("RTE", new NullPointerException("NPE"));

输出:

Error:
java.lang.RuntimeException: RTE
    at Main.main(Main.java:10)

为什么在这种情况下没有记录NullPointerException?

注意:e.printStackTrace() 在两种情况下都会打印两个异常:

java.lang.RuntimeException: RTE
    at Main.main(Main.java:10)
Caused by: java.lang.NullPointerException: NPE
    ... 1 more

版本:

slf4j-api: 1.7.12
slf4j-log4j12: 1.7.12
log4j: 1.2.17

推荐答案

我注意到在我使用的 log4j.properties 文件中有以下行:

log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer

这似乎导致在记录异常时省略 caused by 元素.

删除后,将记录完整的堆栈跟踪.

本文地址:https://www.itbaoku.cn/post/1574992.html

问题描述

First example:

public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws Exception {
        try {
            throw new RuntimeException(new NullPointerException("NPE"));
        } catch (RuntimeException e) {
            logger.error("Error:", e);
        }
    }
}

Output:

Error:
java.lang.RuntimeException: java.lang.NullPointerException: NPE
    at Main.main(Main.java:10)

In the second example we just add a message to the RuntimeException also:

throw new RuntimeException("RTE", new NullPointerException("NPE"));

Output:

Error:
java.lang.RuntimeException: RTE
    at Main.main(Main.java:10)

Why is NullPointerException not logged in this case?

Note: e.printStackTrace() prints both exceptions in both cases:

java.lang.RuntimeException: RTE
    at Main.main(Main.java:10)
Caused by: java.lang.NullPointerException: NPE
    ... 1 more

Versions:

slf4j-api: 1.7.12
slf4j-log4j12: 1.7.12
log4j: 1.2.17

推荐答案

I noticed that in the log4j.properties file I'm using there is the following line:

log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer

It seems to be causing the caused by elements to be omitted when the exception is logged.

Once removed, the full stack trace is logged.