log4j not printing the stacktrace for exceptions

Actually, it's probably due to a hotspot optimization: after a certain number of the same exception being thrown it stops printing out trace. This can be turned off with a VM arg, see:

From http://www.oracle.com/technetwork/java/javase/relnotes-139183.html :

The compiler in the server VM now provides correct stack backtraces for all "cold" built-in exceptions. For performance purposes, when such an exception is thrown a few times, the method may be recompiled. After recompilation, the compiler may choose a faster tactic using preallocated exceptions that do not provide a stack trace. To disable completely the use of preallocated exceptions, use this new flag: -XX:-OmitStackTraceInFastThrow.

More here:

http://jawspeak.com/2010/05/26/hotspot-caused-exceptions-to-lose-their-stack-traces-in-production-and-the-fix/


What you have posted should display the stack trace as stated in the javadoc.

Note that if you don't include a message (and just call logger.error(ex)) then the stack trace is not logged.


There are two overloaded methods for error method.

  1. logger.error(ex);
  2. logger.error("some oops string ", ex);

if you use 1st method , which will only print the name of the Exception. if you use 2nd method, some message along with exception which will print complete stack trace similar to e.printStackTrace() method.