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

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

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 *