Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting stacktrace in logger

I am using log4j to log my exceptions. I want to log whatever I get in e.printStackTrace();
My code looks like this:

try {

} catch(Exception e) {
    log.error("Exception is:::" + e);
}

But the content I get logged looks like this:

2012-02-02 12:47:03,227 ERROR [com.api.bg.sample] - Exception in unTech:::[Ljava.lang.StackTraceElement;@6ed322
2012-02-02 12:47:03,309 ERROR [com.api.bg.sample] - Exception is :::java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

But the content I expect is:

java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(Unknown Source)
at java.util.zip.GZIPInputStream.<init>(Unknown Source)
at java.util.zip.GZIPInputStream.<init>(Unknown Source)
at com.api.bg.sample.unGZIP(sample.java:191)
at com.api.bg.sample.main(sample.java:69)

I tried e.getMessage(), e.getStackTrace(); however I don't get the full stacktrace. Any suggestions?

like image 808
Geek Avatar asked Feb 02 '12 17:02

Geek


People also ask

How do you get StackTrace strings?

StackTrace to String with StringWriter Print throwable stack trace and its backtrace to the PrintWriter. Copy print writer content to StringWriter. Use StringWriter. toString() to get stack trace in string format.

Should StackTrace be logged?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.

How do I get full StackTrace in eclipse?

To simplify the accepted answer let us consider a simple notation. Hence you have the entire stack. But MAKE SURE CHECK BOX FOR “limit console output” is NOT checked under run/debug drop down --> console in eclipse preferences. You can use the following code to get more clarity.


4 Answers

You have to use the two argument form

log.error("my logging message", exception)

See http://www.devdaily.com/blog/post/java/how-print-exception-stack-trace-using-log4j-commons for more details.

like image 106
Brian Tarbox Avatar answered Sep 29 '22 23:09

Brian Tarbox


Change your logging statement to:

log.error("Exception is: ", e);
like image 45
Jonathan Avatar answered Sep 30 '22 01:09

Jonathan


It is actualy log4j that prevents the printing of the fulltime stacktrace. You should however set the exception as a second parameter for the error method.

like image 4
Kurt Du Bois Avatar answered Sep 29 '22 23:09

Kurt Du Bois


If you use the below than e.toString() will be called which calls e.getMessage()

log.error("Exception is:::" + e);

However, to print full stack trace you can use the below:

log.error("Exception is:::" + ExceptionUtils.getStackTrace(e));

where ExceptionUtils is imported as org.apache.commons.lang3.exception.ExceptionUtils

like image 1
Arun Avatar answered Sep 29 '22 23:09

Arun