如何将堆栈跟踪发送到log4j?

2022-08-31 06:59:55

假设您捕获了一个异常,并在标准输出(例如控制台)上获得了以下内容,如果您执行 e.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)

现在我想把它发送给一个记录器,比如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

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

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

由 log4j 来呈现堆栈跟踪。


答案 2

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

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);

推荐