Java web: how to redirect stacktrace of an uncaught exception to a log file?

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

+4
source share
2 answers

Set a Thread.UncaughtExceptionHandler , which prints to the desired file. printStackTrace is thread safe, so multiple threads can have the same PrintStream .

+8
source

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

Exit

***** Yes, caught the Exception ***** java.lang.ArithmeticException: / by zero in thread.UncaughtException.main (UncaughtException.java:12)

+4
source

All Articles