问题

假如你做了ae.printStackTrace(),你就会抓住异常并在标准输出上(例如控制台)获得以下内容:

java.io.FileNotFoundException: so.txt
        at java.io.FileInputStream.<init>(FileInputStream.java)
        at ExTest.readMyFile(ExTest.java:19)
        at ExTest.main(ExTest.java:7)

现在我想把它发送给logger,比如log4j,以获得以下内容:

31947 [AWT-EventQueue-0] ERROR Java.io.FileNotFoundException: so.txt
32204 [AWT-EventQueue-0] ERROR    at java.io.FileInputStream.<init>(FileInputStream.java)
32235 [AWT-EventQueue-0] ERROR    at ExTest.readMyFile(ExTest.java:19)
32370 [AWT-EventQueue-0] ERROR    at ExTest.main(ExTest.java:7)

我怎样才能做到这一点?

try {
   ...
} catch (Exception e) {
    final String s;
    ...  // <-- What goes here?
    log.error( s );
}

#1 热门回答(229 赞)

你将异常直接传递给记录器,例如

try {
   ...
} catch (Exception e) {
    log.error( "failed!", e );
}

由log4j来渲染堆栈跟踪。


#2 热门回答(7 赞)

如果要在不涉及异常的情况下记录堆栈跟踪,请执行以下操作:

String message = "";

for(StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {                         
    message = message + System.lineSeparator() + stackTraceElement.toString();
}   
log.warn("Something weird happened. I will print the the complete stacktrace even if we have no exception just to help you find the cause" + message);

#3 热门回答(7 赞)

你还可以通过ExceptionUtils.getStackTrace将堆栈跟踪作为字符串。

请参阅:ExceptionUtils.java

我只用它log.debug,保持log.error简单。


原文链接