How to convert StackTrace to String

We are all used to print stacktraces to console or in log files. At times we have a need to convert Stacktrace to String to send to another logging system or for related purpose. Let’s see what are the options available to achieve this

Option 1 : Using a PrintWriter

public static String getStackTraceAsString(Throwable cause) {
    StringWriter exceptionWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(exceptionWriter);
    cause.printStackTrace(writer);
    return exceptionWriter.toString();
  }

The printStackTrace() API takes a PrintWriter using which it prints the stack trace. We use this hack and provide a StringWriter wrapped in PrintWriter. We then return the content of StringWriter back as String which contains the stack-trace as a String.

Option 2: Using StringBuilder

public static String getStackTraceAsString(Throwable cause, String lineSeparator) {
    StringBuilder stringBuilder = new StringBuilder();

    for(StackTraceElement stackTraceElement : cause.getStackTrace()) {
      stringBuilder.append(stackTraceElement);
      stringBuilder.append(lineSeparator);
    }

    return stringBuilder.toString();
  }

This code is fairly simple, we iterate through the StackTraceElement Array and append the contents to a StringBuilder. We take lineSeparator as an argument so that we can format the stacktrace in human readable format.

Option 3: Using Commons Lang

Apache Commons Lang library has ExceptionUtils class which provides these function out of box. It also has few more methods which are worth using.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.