使用 log4j 在 Java 中记录运行时异常 [英] Log runtime Exceptions in Java using log4j

查看:28
本文介绍了使用 log4j 在 Java 中记录运行时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Tomcat、Spring 和 JAVA 构建应用程序.我使用 Log4J 作为我的日志库.我目前正在将所有内容记录到文本文件中.我遇到的问题之一是 RuntimeExceptions 没有被记录到任何文件中.我想知道是否有办法记录所有可能抛出到我的应用程序日志文件的 RuntimeExceptions.如果不是,是否可以将其记录到另一个日志文件中?有没有标准的方法来做到这一点?如果是这样,在 Tomcat 中运行您的应用程序时是否有标准的方法来执行此操作?

I am currently building an application using Tomcat, Spring and JAVA. I am using Log4J as my logging library. I currently am logging everything to a text file. One of the issues I'm having is that RuntimeExceptions are not being logged to any files. I was wondering if there is a way to log all RuntimeExceptions that maybe thrown to my application log file. If not is it possible to have it log to another log file? Is there a standard way to do this? If so is there a standard way to do this when running your application within Tomcat?

预先感谢您的帮助!

推荐答案

我不确定这是否是您要查找的内容,但是有一个用于终止线程的异常处理程序.它是线程目标未明确捕获的任何异常的处理程序.

I'm not sure if this is what you are looking for, but there is a handler for exceptions that terminate threads. It is a handler for any exception that is not caught explicitly by the target of the thread.

默认的未捕获异常处理程序"只是调用 Throwable 上的 printStackTrace() 将堆栈跟踪打印到 System.err.但是,您可以 用你自己的>UncaughtExceptionHandler 将异常记录到 log4j:

The default "uncaught exception handler" simply calls printStackTrace() on the Throwable to print the stack trace to System.err. However, you could replace this with your own UncaughtExceptionHandler that logs the exception to log4j instead:

class Log4jBackstop implements Thread.UncaughtExceptionHandler {

  private static Logger log = Logger.getLogger(Log4jBackstop.class);

  public void uncaughtException(Thread t, Throwable ex) {
    log.error("Uncaught exception in thread: " + t.getName(), ex);
  }

}

如果您正在使用传递 Runnable 对象的执行器框架,则其线程可能有自己的 catch 块,以防止异常到达未捕获的异常处理程序.如果您想在那里捕获 Runtime 异常,一种方法是将每个任务包装在日志包装器中,如下所示:

If you are using an executor framework to which you pass a Runnable object, its threads probably have their own catch block that prevent exceptions from reaching the uncaught exception handler. If you want to catch Runtime exceptions there, one way to do it is to wrap each task in a logging wrapper, like this:

class Log4jWrapper {

  private final Logger log;

  private final Runnable target;

  Log4jWrapper(Logger log, Runnable target) { 
    this.log = Objects.requireNonNull(log);
    this.target = Objects.requireNonNull(target); 
  }

  public void run() {
    try {
      target.run();
    } catch(RuntimeException ex) {
      log.error("Uncaught exception.", ex);
      throw ex;
    }
  }

}

...

Runnable realTask = ...;
executor.submit(new Log4jWrapper(Logger.getLogger(Whatever.class), realTask));

这篇关于使用 log4j 在 Java 中记录运行时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆