Labels

Friday, 15 October 2010

Getting Stack Trace from Throwables as String

Problem:
We want to get the stack trace of a Throwable (Errors or Exceptions) in a String format.
Why we want that:
We wanted to log it using log4j at the Debug level.

Solution:

1. Use the getStackTrace() method:

This method returns an array of StackTraceElement objects. As per the Java Docs "Each object represents represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. Typically, this is the point at which the throwable corresponding to the stack trace was created."

This way isn't very good for our needs. we just want a String looking like the one you get from call printStackTrace() and in order to do that, we will have to get the exception message using
getMessage() or getLocalizedMessage() and then loop through the StrackTraceElement array to get the trace.

This solution might be good for other uses but definitely not for this one.

2. Read the actual output of printStackTrace() method:

The printStackTrace() method has an overloaded version printStackTrace(PrintWriter s) , this method - as per JavaDocs - "Prints this throwable and its backtrace to the specified print writer".

String getStackTrace(final Throwable pThrowable) {

String stackTrace = null;
StringWriter stringWriter = null;
PrintWriter printWriter = null;

try {
stringWriter = new StringWriter();
printWriter = new PrintWriter(stringWriter);
pThrowable.printStackTrace(printWriter);
stackTrace = stringWriter.getBuffer().toString();
} catch (Throwable t) {
stackTrace = null;
} finally {
if (printWriter != null) {
printWriter.close();
}
}
return stackTrace;
}
This method will return the stack trace in a String format.

Thank you for reading.

No comments:

Post a Comment