How to send a stacktrace to log4j?
You pass the exception directly to the logger, e.g.
try { ...} catch (Exception e) { log.error( "failed!", e );}
It's up to log4j to render the stack trace.
If you want to log a stacktrace without involving an exception just do this:
String message = "";for(StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) { message = message + System.lineSeparator() + stackTraceElement.toString();} log.warn("Something weird happened. I will print the the complete stacktrace even if we have no exception just to help you find the cause" + message);
You can also get stack trace as string via ExceptionUtils.getStackTrace
.
See: ExceptionUtils.java
I use it only for log.debug
, to keep log.error
simple.