背景:本来想集成个日志记录,这次用的springboot内置的log4j,结果发现运行时候报的异常无法写入到日志文件,不禁感叹,我就是为了记录错误,结果你记不进去,要你有何用?然后就开始了漫长的百度过程,发现好多都是答非所问,真是服了
一、日志配置不是本次重点,简单介绍一下吧:
#yml中配置log配置
logging:
level:
#com包下为error级别
com: error
#日志输出文件名,这样配置会建立文件在项目根目录
file:
name: handlerlogging.log
在需要打印或者记录日志的地方这样就可以啦
public class MyUncaughtExceptionHandler {
private static Logger log = LoggerFactory.getLogger(MyUncaughtExceptionHandler .class);
public void uncaughtException(Thread t, Throwable ex) {
log.error("Uncaught exception in thread: " + t.getName(), ex);
}
}
二、将异常记录在日志中
默认情况下,如果运行时抛出未捕获异常,会打印在控制台,不过我总不可能一直盯着吧,所以还是要想办法记录到日志文件
1.创建为捕获异常拦截器
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private static Logger log = LoggerFactory.getLogger(MyUncaughtExceptionHandler .class);
public void uncaughtException(Thread t, Throwable ex) {
log.error("Uncaught exception in thread: " + t.getName(), ex);
}
}
2.将自定义拦截器设置到当前线程的DefaultUncaughtExceptionHandler
Thread.currentThread().setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
以上两步就可以达到目的
三、测试
直接在springboot入口程序,手动抛出一个异常,可以发现已经记录到log文件中
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
Thread.currentThread().setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
throw new RuntimeException();
}
}