java web:如何将未捕获的异常的堆栈跟踪重定向到日志文件?

发布于 2024-08-09 06:13:59 字数 55 浏览 1 评论 0原文

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

I want to redirect only stacktrace of uncaught exception from console to log file. The rest of the things should appear on console as usual.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蘸点软妹酱 2024-08-16 06:13:59

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

Set a Thread.UncaughtExceptionHandler that prints to the desired file. printStackTrace is threadsafe, so several threads may share the same PrintStream.

天生の放荡 2024-08-16 06:13:59

为此创建了一个示例程序,感谢 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)

Created a sample program for this, Thanx to 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 
    }
}

Output is

*****Yeah, Caught the Exception***** java.lang.ArithmeticException: / by
zero at
thread.UncaughtException.main(UncaughtException.java:12)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文