我不确定这是否是您要查找的,但是有一个用于终止线程的异常的处理程序。它是线程目标未显式捕获的任何异常的处理程序。
默认的“未捕获异常处理程序”只是调用 将堆栈跟踪打印到 。但是,您可以将其替换为您自己的UncaughtExceptionHandler,该Handler
将异常记录到log4j中:printStackTrace()
Throwable
System.err
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
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));