简体   繁体   English

如何使用 log4j 在 java 中记录所有未捕获的异常

[英]How to log all uncaught exceptions in java using log4j

I want to log the exceptions in my server side java program.我想在我的服务器端 java 程序中记录异常。 Is there any way to catch all exceptions that have not been caught using an existing try catch?有没有办法使用现有的 try catch 捕获所有未捕获的异常?

I thought about doing a try catch in my main executor and log the exception the catch but I got a problem: exceptions on other threads haven't been caught.我想过在我的主执行程序中做一个 try catch 并将异常记录到 catch 但我遇到了一个问题:其他线程上的异常没有被捕获。

Each thread can have an UncaughtExceptionHandler , which is called when an exception reaches the bottom of the thread's call stack.每个线程都可以有一个UncaughtExceptionHandler ,当异常到达线程调用堆栈的底部时调用它。 The default implementation prints a message on the standard error.默认实现在标准错误上打印一条消息。

You can change the default handler with:您可以使用以下命令更改默认处理程序:

  private static final Logger logger = LogManager.getLogger();

  public static void main(String[] args) throws IOException {
    Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
      logger.warn("Uncaught exception in thread {}.", t, e);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM