log4j not printing the stacktrace for exceptions

2019-01-17 02:16发布

I am using log4j with tomcat. When I log exceptions in my JSPs, servlets:

private Logger _log = Logger.getLogger(this.getClass());
...
try{...} catch (Exception e) {
    _log.error("Error refreshing all prices", e);
}

I only get the first line of the exception, without a stacktrace.

17-Feb 17:37:45 ERROR AutoContrib:175 - Exception while publishing csv file: java.lang.ArrayIndexOutOfBoundsException

Not very helpful at all!

My log4j.properties file (/tomcat/common/classes/log4j.properties) looks like this:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd-MMM HH:mm:ss} %5p %c{1}:%L - %m%n
log4j.appender.stdout.threshold=info

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=5000KB
log4j.appender.file.maxBackupIndex=10
log4j.appender.file.File=${catalina.home}/logs/web.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MMM HH:mm:ss} %5p %c{1}:%L - %m%n
log4j.appender.file.threshold=info

log4j.rootLogger=debug, stdout, file

8条回答
够拽才男人
2楼-- · 2019-01-17 03:01

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.

查看更多
The star\"
3楼-- · 2019-01-17 03:08

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/

查看更多
登录 后发表回答