How to convert StackTrace to String

Recently we had a requirement in our application that whenever an exception occurred we   need to store all StackTrace elements in the application’s log file. So we need to get a string representation of the  StackTrace.

Starting by searching in java.lang.Throwable class, we have found two methods   printStackTrace(PrintWriter)  which prints the throwable and its backtrace to the specified print writer, and printStackTrace(PrintStream) which prints the throwable and its backtrace to the specified print stream. So which method best fit our case?

To answer this question we referred to API documentation for PrintStream and PrintWriter classes and we found this statement:

All characters printed by a PrintStream are converted into bytes using the platform’s default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.

So our choice was printStackTrace(PrintWriter)  method and here is the method we used.

import java.io.PrintWriter;
import java.io.StringWriter;

...........................................

...........................................

public String getStackTrace(Exception e){
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
Advertisements

1 Comment

Filed under Java

One response to “How to convert StackTrace to String

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s