假设您捕获了一个异常,并且如果您执行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 );
}
发布于 2010-12-04 00:48:57
您可以将异常直接传递给记录器,例如
try {
...
} catch (Exception e) {
log.error( "failed!", e );
}
由log4j来渲染堆栈跟踪。
发布于 2014-08-28 23:38:28
如果您想在不涉及异常的情况下记录堆栈跟踪,只需执行以下操作:
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);
发布于 2012-02-23 10:42:00
您还可以通过ExceptionUtils.getStackTrace
以字符串形式获取堆栈跟踪。
为了保持log.error
的简单性,我只将它用于log.debug
。
https://stackoverflow.com/questions/4347797
复制相似问题