问题描述
第一个例子:
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 元素.
删除后,将记录完整的堆栈跟踪.
问题描述
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.