Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j does not print stack trace

Tags:

java

log4j

I catch NullPointerException but log4j does not print stack trace, I aspect number of line of exception occurred etc. what is wrong?

My log

20110412-101042,317[ Timer-7][R] Exception while processing for value: abc.                  [xyz.Dummy]
java.lang.NullPointerException

log4j.property file

log4j.rootCategory=ERROR, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p %r [%t] : %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=my_application.log
log4j.appender.logfile.Append=true
log4j.appender.logfile.MaxBackupIndex =10
log4j.appender.logFile.MaxFileSize=40000KB
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyyMMdd-HHmmss,SSS}[%8.8t][%.1p] %-70m[%c{2}]%n

My snippet code

String value;
try {
   value = "abc";
   //... lots for code
}catch(Exception e) {
   logger.error("Exception while processing for value: " + value + ". ", e);
}
like image 360
Erdinç Taşkın Avatar asked Apr 14 '11 11:04

Erdinç Taşkın


People also ask

How to print the stack trace in Log4J?

The short answer is that all you have to do to print the stack trace of an exception using Java and Log4J (or the Apache Commons Logging project) is this: log. error("Your description here", exception); where exception is your Java Exception object.

How do you get Stacktrace strings?

Example: Convert stack trace to a stringIn the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer. Then, we simply convert it to string using toString() method.

How do I print an exception message?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

How do you log in Stacktrace of exception?

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);


1 Answers

The problem is the %-70m in your Layout. It truncates the message, and therefore does not reach the stacktrace. Use %m as usual instead.

Even Better: Write a custom layout, this will work as you want.

like image 111
Daniel Avatar answered Sep 28 '22 09:09

Daniel