Wednesday, May 20, 2009

Redirect stack trace to log file

Log4j logging is a powerful way of debugging production issues. Here is a simple way to redirect your stack trace to log file. Typically stack trace should provide all information necessary to the developer esp. during NullPointers when e.getMessage() will not print anything more than in the output logs.

public static Log log = LogFactory.getLog(file.class);
try{
//risky operation
} catch (Exception e) {
ByteArrayOutputStream bsos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bsos);
e.printStackTrace(ps);
log.error(e.getMessage() + bsos.toString());
}finally{
//cleanup
}

You can opt for a more detailed approach of logging every System.out in your application to the log file using the approach described in Nick's blog

No comments:

Post a Comment

Thank you for your feedback