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

查看:1130
本文介绍了使用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.

默认的未捕获的异常处理程序只调用 printStackTrace () Throwable 上将堆栈跟踪打印到 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天全站免登陆