Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 253
Thejesh GN Avatar asked Oct 21 '09 09:10

Thejesh GN


2 Answers

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

like image 82
gustafc Avatar answered Oct 31 '22 20:10

gustafc


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)

like image 44
Rakesh Juyal Avatar answered Oct 31 '22 19:10

Rakesh Juyal