Reputation: 189786
I need to take a caught exception and get a String that is what would be printed using printStackTrace()
.
It looks like the simplest thing is to call printStackTrace(X)
, where X subclasses a PrintStream
or PrintWriter
, and gathers it to a StringBuilder
and can return a String
.
Does such a thing exist? If not, any suggestions how to do this?
edit: skaffman posted a solution that used getStackTrace()
. (can you or moderators undelete?) This is actually the only solution that works "right". The problem with using PrintWriter on top of StringWriter, although it works easily, is that for deep stack traces it doesn't print all the elements.
Upvotes: 0
Views: 1364
Reputation: 40851
Guava contains this in its com.google.common.base.Throwables class:
public static String getStackTraceAsString(Throwable throwable) {
StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
Upvotes: 0
Reputation: 403551
How about, instead of printStackTrace
, you call Throwable.getStackTrace()
, which returns StackTraceElement[]
? You still need to do some work to get it into a String, but it's arguably a cleaner solution than hacking about with string buffers and the like.
Once you have the StackTraceElement[]
, you can manipulate that. It may be that the layout as dictated by printStackTrace
isn't really suitable for what you're going to use it for, and that more explicit formatting as provided by the StackTraceElement
object model gives you more control. That is what it was provided for, after all.
Upvotes: 2
Reputation: 40851
What you want is StringWriter
You can pass that into the constructor of a PrintWriter and then call getBuffer() on to the StringWriter or toString() to get the final string.
Upvotes: 4