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