Log4J exception example - How to print the stack trace of an exception using Log4J (or Commons Logging)

Submitted by alvin on September 8, 2008 - 12:53pm

tags: 

Log4J exception FAQ: "How do I print the stack trace of an exception using Log4J or Commons Logging?" 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 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 exception object. The error method that takes a description followed by a Throwable will print the stack trace of the Throwable.