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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s