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

查看:98
本文介绍了当包装程序异常包含消息时,带有Log4j的Slf4j不会打印包装的异常(由)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个示例:

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添加了一条消息:

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

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

输出:

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

为什么在这种情况下未登录NullPointerException?

Why is NullPointerException not logged in this case?

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

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

版本:

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

推荐答案

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

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

log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer

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

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.

这篇关于当包装程序异常包含消息时,带有Log4j的Slf4j不会打印包装的异常(由)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆