Proper use of Log4J for logging exceptions

I see a lot of developers at my organization who are using Log4J incorrectly when it comes to logging exceptions.

Invariably, the desire is to log the error and get a meaningful message from the exception that is thrown.

Consider the following code:

Logger log = Logger.getLogger(ClassName.class);
try
{
    //Some code here...
}
    catch(SomeException e)
{
    log.error("Some error has occurred");
}

This block of code sets up the context for our example.¬† We’ll just worry about the log.error statement from here on.

The most common errors I see in logging exceptions are:


log.error(e);

and


log.error("An error has occurred: " + e.getMessage());

Unfortunately, neither of these calls will generate the output that the developer wants.

Ultimately, the developer wants to get a meaningful message that will help them identify and debug the problem.
Log4J does provide a simple way to generate a full stack trace for an exception in your logs:

log.error(String msg, Throwable e)

So you could modify the incorrect examples I listed above to do what you really want:

log.error("Some Error Message", e);

This code will generate an entry in the log that contains your error message AND a full stack trace for the exception that was caught.

Leave a Reply

Your email address will not be published. Required fields are marked *