I need to log a stack trace when I catch an exception in my Java app. I know that exceptions have a built in printStackTrace()
method, and that that can send the stack trace to a different PrintWriter/PrintStream, but it would be useful if I could grab the stack trace as a String so that I can manipulate it or display it in a JMessagePane or something. Currently, the only way I have to do this is:
String stackTrace = "";
stackTrace += e.getClass().getName() + ": " + e.getMessage() + "\n";
for (StackTraceElement elt : e.getStackTrace()) {
stackTrace += "\tat " + elt + "\n";
}
Is there a cleaner way to do this?
There is:
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();
using commons-lang :
String stackTrace = ExceptionUtils.getStacktrace(e);
javadoc : ExceptionUtils.html#getStackTrace()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With