I am currently building an application using Tomcat, Spring and JAVA. I am using Log4J
as my logging library. I currently am logging everything to a text file. One of the issues I'm having is that RuntimeExceptions
are not being logged to any files. I was wondering if there is a way to log all RuntimeExceptions
that maybe thrown to my application log file. If not is it possible to have it log to another log file? Is there a standard way to do this? If so is there a standard way to do this when running your application within Tomcat?
Thank you in advance for your help!
I'm not sure if this is what you are looking for, but there is a handler for exceptions that terminate threads. It is a handler for any exception that is not caught explicitly by the target of the thread.
The default "uncaught exception handler" simply calls
printStackTrace()
on theThrowable
to print the stack trace toSystem.err
. However, you could replace this with your ownUncaughtExceptionHandler
that logs the exception to log4j instead:If you are using an executor framework to which you pass a
Runnable
object, its threads probably have their owncatch
block that prevent exceptions from reaching the uncaught exception handler. If you want to catchRuntime
exceptions there, one way to do it is to wrap each task in a logging wrapper, like this:You can try redirecting the StdErr to use your logger. This should output the result of anything being written to your std err (which should include unhandled exceptions)
This blog post gives a good rundown on how to do the redirection into a FileHandler that is apart of your logger.
https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and
One way to log uncaught RuntimeExceptions (or any uncaught Throwables for that matter) is to create a class that implements Thread.UncaughtExceptionHandler. This class's
uncaughtException()
method would simply write the exception details to the log. You can make the JVM call this exception handler whenever an uncaught RuntimeException terminates a thread by adding the lineto your code.