springboot日志没有记录异常问题及解决
作者:FlowingRiver
在Spring Boot项目中,定时任务在服务器上运行时报错但未记录日志,本地运行时控制台能打印报错信息,但日志中无记录,问题出在报错发生在线程池中,通过继承ThreadPoolExecutor并重写afterExecute方法,可以将异常信息记录到日志中
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<>());
日志中就有异常信息了。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。