|
"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.
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.
For more information on how this works with Log4J I recommend looking at the API documentation for the Logger class.
A more complete example
If that's not enough, a 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 example the variable log refers to my Log4J logger reference, which I create somewhere earlier in the code.
Of course if you're using the warn or debug methods just call those methods instead. Here's the debug method example:
log.debug("Your description here", exception);
and here's the warn method syntax:
log.warn("Your description here", exception);
|