How to Convert a Stack Trace to a String

How can I convert a stack trace to a string?

One can use the following method to convert an Exception stack trace to String. This class is available in Apache commons-lang which is most common dependent library with many popular open sources

org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)

How to convert a StackTraceElement[] to a String?

It is super easy, you just have to print them, with whatever prefix you want.

To print same as printStackTrace(), the prefix would be "\tat ".

Proof

// Show printStackTrace() output
new RuntimeException().printStackTrace(System.out);

// Similar output using getStackTrace()
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
System.out.println("getStackTrace()");
for (int i = 1; i < stackTrace.length; i++)
System.out.println("\tat " + stackTrace[i]);

Output

java.lang.RuntimeException
at Test.main(Test.java:5)
getStackTrace()
at Test.main(Test.java:8)

Note how for loop skipped index 0, since that is the stack frame for getStackTrace() itself.

How can I convert a stack trace to a string?

One can use the following method to convert an Exception stack trace to String. This class is available in Apache commons-lang which is most common dependent library with many popular open sources

org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)

Stack trace as String

You need to call the Throwable#printStackTrace(PrintWriter);

try{

}catch(Exception ex){
String message = getStackTrace(ex);
}

public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}

You can also use commons-lang-2.2.jar Apache Commons Lang library which provides this functionality:

public static String getStackTrace(Throwable throwable)
Gets the stack trace from a Throwable as a String.

ExceptionUtils#getStackTrace()

Turn a stack trace into a string?

I'm not sure if StackTraceElement is emulated, but if it is you can run something like

for (StackTraceElement element : exception.getStackTrace()) {
string += element + "\n";
}

How to store printStackTrace into a string

Something along the lines of

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

Ought to be what you need.

Relevant documentation:

  • StringWriter
  • PrintWriter
  • Throwable

Restore stack trace from string

Thank you Dylan for your answer! I discussed it with my colleagues and we found another solution:

Our idea was to split up the stack trace elements and to merge it to a string:

    StringBuilder stackTraceStringBuilder = new StringBuilder();
for (StackTraceElement stackTraceElement : exception.getStackTrace())
stackTraceStringBuilder.append(String.format("%s|%s|%s|%d\n", stackTraceElement.getClassName(), stackTraceElement.getMethodName(), stackTraceElement.getFileName(), stackTraceElement.getLineNumber()));
this.stackTrace = stackTraceStringBuilder.toString();

To restore the string to a stack trace element is quite simple:

    RuntimeException runtimeException = new RuntimeException(message);
String[] stackTraceRows = stackTrace.split("\n");
StackTraceElement[] stackTraceElements = new StackTraceElement[stackTraceRows.length];
for (int i = 0; i < stackTraceRows.length; i++) {
String[] stackTraceRow = stackTraceRows[i].split("\\|");
stackTraceElements[i] = new StackTraceElement(stackTraceRow[0], stackTraceRow[1], stackTraceRow[2], Integer.parseInt(stackTraceRow[3]));
}
runtimeException.setStackTrace(stackTraceElements);

Anyway, the solution of Dylan looks better, but I dont want to withhold this option.

e.printStackTrace(); in string

Use the following piece of code:

Writer writer = new StringWriter();
exception.printStackTrace(new PrintWriter(writer));
String s = writer.toString();

There used to be a way to extract an exception stacktrace into the String in one line with Log.getStackTraceString call. But starting from Android 4.0 (API 14) that method is not reliable anymore, as it returns an empty string for UnknownHostException (see Android issue #21436 for the details, in short: "to reduce the amount of log spew that apps do in the non-error condition of the network being unavailable" Android engineers made IMHO a dubious decision to modify Log.getStackTraceString method).

Thus it is better to use the code I provided at the beginning of this post.

Stack trace as a string

runtime.Stack() puts a formatted stack trace into a supplied []byte. You can then convert that to a string.

You can also use debug.Stack(), which allocates a large enough buffer to hold the entire stack trace, puts the trace in it using runtime.Stack, and returns the buffer ([]byte).



Related Topics



Leave a reply



Submit