How to print an exception stack trace using Log4J (or Commons Logging)

Log4J exception FAQ: "How do I print the stack trace of an exception using Log4J or Commons Logging?"

Printing the stack trace of a Log4J exception seems to be something of a trick question. In reviewing Java code from different developers at different organizations I see a lot of people working very hard to print a stack trace using Log4J, including a lot of variations of calling e.printStackTrace() method. In this short tutorial I’ll show how to solve this problem.

Log4J exception stack trace - short answer

The short answer is that all you have to do to print the stack trace of an exception using Java and Log4J (or the Apache Commons Logging project) is this:

log.error("Your description here", exception);

where exception is your Java Exception object. The Log4j error method that takes a description followed by a Throwable will print the stack trace of the Java Throwable object.

For more information on how this works with Log4J I recommend looking at the API documentation for the Logger class.

A more complete Log4J exception stack trace example

In case that isn’t clear, the following source code might help to make what I’m saying more clear:

  // do something here that might throw an exception
catch (BadException e)
  log.error("Threw a BadException in MyClass::MyMethod, full stack trace follows:", e);

In these Log4j exception printing examples, the variable named log refers to my Log4J logger reference, which I create somewhere earlier in the code.

Of course if you're using the Log4j warn or debug methods you'll just call those methods instead of the error method. Here's a Log4j debug method example:

log.debug("Your description here", exception);

and here's the Log4j warn method syntax:

log.warn("Your description here", exception);

Log4J stack trace printing - What's Related

As I wrap up my current collection of Log4J examples, here's a link to my other Log4J tutorials: