springboot 日志没有记录异常

背景

springboot项目,放到服务器上跑,定时任务运行过程中中断,查看日志却发现没有报错。
在本地跑,发现控制台能打印报错信息,而日志也没有记录报错。

经排查,发现是因为报错出现在线程池中,没有在日志中记录。
原先使用线程池:

ExecutorService executorService = Executors.newFixedThreadPool(15);

解决

新建类继承ThreadPoolExecutor,重写afterExecute方法。

@Slf4j
public class TaskExecutor extends ThreadPoolExecutor {
    public TaskExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t != null) {
            log.error(t.getMessage(), t);
        }
    }
}

使用:

   ExecutorService executorService = new TaskExecutor(10, 15,
            0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>());

日志中就有异常信息了。

你可能感兴趣的:(Java,springboot,多线程,异常,日志)