【问题标题】:java web: how to redirect stacktrace of uncaught exception to a log file?java web:如何将未捕获异常的堆栈跟踪重定向到日志文件?
【发布时间】:2009-10-21 09:10:46
【问题描述】:

我只想将未捕获异常的堆栈跟踪从控制台重定向到日志文件。其余的东西应该像往常一样出现在控制台上。

【问题讨论】:

  • 也许我可以在启动时将 System.err 重定向到日志文件。我猜默认是printstacktrace。可能使用 System.setErr

标签: java logging log4j


【解决方案1】:

Set Thread.UncaughtExceptionHandler 打印到所需文件。 printStackTrace 是线程安全的,因此多个线程可以共享同一个PrintStream。

【讨论】:

  • Gustafc,我从来没有听说过这个东西,但是它就像魅力一样 :)
【解决方案2】:

为此创建了一个示例程序,感谢 gustafc

public class UncaughtException {
    public static void main(String[] args) {        
        Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler(){
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("*****Yeah, Caught the Exception*****");
                e.printStackTrace(); // you can use e.printStackTrace ( printstream ps )
            }
        });     

        System.out.println( 2/0 );  // Throw the Exception 
    }
}

输出是

*****是的,捕获异常***** java.lang.ArithmeticException: / by 零在 thread.UncaughtException.main(UncaughtException.java:12)

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    相关资源
    最近更新 更多