Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java send Stack trace to different output stream

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?

like image 276
ewok Avatar asked Feb 22 '12 22:02

ewok


2 Answers

There is:

StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();
like image 189
Tomasz Nurkiewicz Avatar answered Sep 28 '22 06:09

Tomasz Nurkiewicz


using commons-lang :

String stackTrace = ExceptionUtils.getStacktrace(e);

javadoc : ExceptionUtils.html#getStackTrace().

like image 24
Sébastien Helbert Avatar answered Sep 28 '22 05:09

Sébastien Helbert