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?
log.error(e) <- shows the error, but doesn't show stack trace
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.
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);
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:
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();
I use the ExceptionUtils#getFullStackTrace method of Jakarta Commons Lang
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