在日志记录器中获取堆栈跟踪信息

54

我正在使用log4j记录我的异常。我想记录e.printStackTrace();中的所有内容。
我的代码看起来像这样:

try {

} catch(Exception e) {
    log.error("Exception is:::" + e);
}

但我得到的内容长得像这样:

2012-02-02 12:47:03,227 ERROR [com.api.bg.sample] - Exception in unTech:::[Ljava.lang.StackTraceElement;@6ed322
2012-02-02 12:47:03,309 ERROR [com.api.bg.sample] - Exception is :::java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

但我期望的内容是:

java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(Unknown Source)
at java.util.zip.GZIPInputStream.<init>(Unknown Source)
at java.util.zip.GZIPInputStream.<init>(Unknown Source)
at com.api.bg.sample.unGZIP(sample.java:191)
at com.api.bg.sample.main(sample.java:69)

我尝试使用e.getMessage()e.getStackTrace();,但是我没有得到完整的堆栈跟踪信息。有什么建议吗?


您可以查看下面的线程。它有完整的答案。 https://dev59.com/g2855IYBdhLWcg3wbztl#51655824 - Md. Sajedul Karim
5个回答

90

8

将您的日志语句更改为:

log.error("Exception is: ", e);

4

实际上是 log4j 防止打印完整的堆栈跟踪。然而,您应该将异常作为错误方法的第二个参数进行设置。


3
如果使用下面的方法,将会调用e.toString(),该方法又会调用e.getMessage()。
log.error("Exception is:::" + e);

然而,要打印完整的堆栈跟踪信息,您可以使用以下代码:

log.error("Exception is:::" + ExceptionUtils.getStackTrace(e));

在这里,ExceptionUtils被导入为org.apache.commons.lang3.exception.ExceptionUtils。


0
log.log(LEVEL.ERROR,e.getMessage(),e);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接