小编典典
我不确定这是否是你要寻找的,但是有一个终止线程的异常处理程序。它是线程异常未明确捕获的任何异常的处理程序。
默认“未捕获的异常处理程序”只是调用printStackTrace()上Throwable打印的堆栈跟踪System.err。但是,你可以将其替换为自己的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块,这些块可以防止异常到达未捕获的异常处理程序。如果要在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));
2020-04-18