java将运行时异常(未捕获异常)写入log日志文件

背景:本来想集成个日志记录,这次用的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();
    }
    
}

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值