How to Print Stack Trace of an Exception using Log4j

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.

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.

A more complete Log4j exception stack trace example

If you'd like to see a little more, this slightly more complete example might be more helpful:

try {
  // 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 all these Log4j exception printing examples, the variable "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 log 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);


Popular posts from this blog