我目前正在使用 Tomcat、Spring 和 JAVA 构建应用程序。我使用 Log4J
作为我的日志库。我目前正在将所有内容记录到文本文件中。我遇到的问题之一是 RuntimeExceptions
没有被记录到任何文件中。我想知道是否有办法记录所有可能抛出到我的应用程序日志文件的 RuntimeExceptions
。如果不是,是否可以将其记录到另一个日志文件?有没有标准的方法来做到这一点?如果是这样,在 Tomcat 中运行您的应用程序时是否有标准方法来执行此操作?
提前感谢您的帮助!
最佳答案
我不确定这是否是您要查找的内容,但是有一个用于终止线程的异常处理程序。它是线程目标未显式捕获的任何异常的处理程序。
默认的“未捕获异常处理程序”只是调用 Throwable
上的 printStackTrace()
以将堆栈跟踪打印到 System.err
。但是,您可以 replace这个用你自己的UncaughtExceptionHandler
而是将异常记录到 log4j:
class Log4jBackstop implements Thread.UncaughtExceptionHandler {
private static Logger log = Logger.getLogger(Log4jBackstop.class);
public void uncaughtException(Thread t, Throwable ex) {
log.error("Uncaught exception in thread: " + t.getName(), ex);
}
}
如果您正在使用向其传递 Runnable
对象的执行器框架,则其线程可能具有自己的 catch
block ,以防止异常到达未捕获的异常处理程序。如果您想在那里捕获 Runtime
异常,一种方法是将每个任务包装在日志包装器中,如下所示:
class Log4jWrapper {
private final Logger log;
private final Runnable target;
Log4jWrapper(Logger log, Runnable target) {
this.log = Objects.requireNonNull(log);
this.target = Objects.requireNonNull(target);
}
public void run() {
try {
target.run();
} catch(RuntimeException ex) {
log.error("Uncaught exception.", ex);
throw ex;
}
}
}
...
Runnable realTask = ...;
executor.submit(new Log4jWrapper(Logger.getLogger(Whatever.class), realTask));
关于java - 使用 log4j 在 Java 中记录运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2344654/