Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display stack trace on a caught exception?

I have a generic function that prints exceptions (using log4j):

private void _showErrorMessage(Exception e) {     log.error(e.getClass() + ": " +  e.getMessage() + ": " + e.getCause() + "\n" +  e.getStackTrace().toString()); } 

Instead of seeing the stack trace I'm seeing:

[Ljava.lang.StackTraceElement;@49af7e68 

How can I view the stack trace of the exception properly?

update

log.error(e) <- shows the error, but doesn't show stack trace

like image 789
ufk Avatar asked Feb 11 '10 14:02

ufk


People also ask

How can I get stack trace of exception?

The StackTrace property is overridden in classes that require control over the stack trace content or format. By default, the stack trace is captured immediately before an exception object is thrown. Use StackTrace to get stack trace information when no exception is being thrown.

How do I print exception stack trace in log file?

The function printStackTrace() of the Exception class can take one parameter, either a PrintStream or a PrintWriter. Thus, it is possible, using a StringWriter, to print the stack trace into a String: StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e. printStackTrace(pw);


2 Answers

Your logging framework should have the ability to log exceptions, so simply passing the exception to the proper .error(Object, Throwable) call should be enough:

  • log4j can do it
  • commons logging can do it
  • java.util.logging can do it

If your logging framework can't do that, or you need the stack trace in a String for any other reason, then it becomes a bit harder. You'll have to create a PrintWriter wrapping a StringWriter and call .printStackTrace() on the Exception:

StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); String stacktrace = sw.toString(); 
like image 142
Joachim Sauer Avatar answered Sep 22 '22 15:09

Joachim Sauer


I use the ExceptionUtils#getFullStackTrace method of Jakarta Commons Lang

like image 42
Guillaume Avatar answered Sep 21 '22 15:09

Guillaume