[英]java web: how to redirect stacktrace of uncaught exception to a log file?
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.
其余的东西应该像往常一样出现在控制台上。
Set a Thread.UncaughtExceptionHandler
that prints to the desired file. 设置一个
Thread.UncaughtExceptionHandler
,打印到所需的文件。 printStackTrace
is threadsafe, so several threads may share the same PrintStream
. printStackTrace
是线程安全的,因此多个线程可以共享同一个PrintStream
。
Created a sample program for this, Thanx to gustafc 为此创建了一个示例程序,Thanx到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)
*****是的,抓住了异常***** java.lang.ArithmeticException:/在thread.UncaughtException.main上为零(UncaughtException.java:12)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.