0


I'm using slf4j/log4j in my java application.
My problem is that for now I'm able only to log exceptions stack traces calling the appropriate logger method in the catch section of a try catch like:

catch (AnException ex) {
    logger.error("An exception occurred", ex); 
}

I would like to put in the log file also the runtime exception for which I didn't put any cacth, like NullPointerException or NumberFormatException.
As they are shown in the console I guess that there is a manner to redirect this stream from the console to the SLF4J logger.
Anyone know how can I do it?

user2572526
  • 1,219
  • 2
  • 17
  • 35

2 Answers2

2

If you want to log unchecked exceptions, catch RuntimeException and log them.
To log all exceptions, catch Exception and log them.
To also log errors, catch Throwable and log them.

For command-line programs, you'd likely want to do this in the main() method, in a try block started after initializing the logging framework.

If you use threads, you'd want to do this in the run() method of the Runnable / Thread.

In a Servlet web application, you might do that in a Filter, and rethrow the exception so container can handle error correctly.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Hi, thanks for your answer, it should work. BTW I guess if there is a better way to manage it, this seems a bit a workaround. I will wait to see if anyone has a better idea then eventually mark your as the choosen answer – user2572526 Dec 13 '16 at 13:26
0

I would like to highlight an other solution that works for uncaught exceptions globally in your application, without wrapping with try/catch blocks each time.

Threads have an field called uncaughtExceptionHandler used whenever an uncaught exception rises. This field can be overridden using the method Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler) once in your startup main method for instance. Each time an uncaught exception rises your custom UncaughtExceptionHandler will be used to handle it.

Check this post for more details.

Youssef NAIT
  • 1,362
  • 11
  • 27