Friday, January 28, 2011

How to log an exception's stackTrace to log file using logger

Manytimes, we use logger to log messages that help us while debugging our application.
But, do you know, how do we write exception stackTrace to log file?

I tried to look for methods in Exception object, there is a method that writes to PrintWriter. Now how do I get PrintWriter's Object? Definitely, i could use reponse.getWriter(), but what if i want to log stacktrace from a java file, where I do not have access to response object. Moreover in many scenario's I would not like to write the stacktrace to browser, visible to end user.

Then I found a very useful over loaded method, which got skipped everytime before today.

Logger has an overloaded method, with 2 arguments, the second one is object of Throwable or Exception class.

This can be achieved as follows

 ...
 } catch( Exception e ) {
 logger.debug( e.getMessage(), e );
 }
 ...

No comments:

Post a Comment