Logged exception missing stack trace in Log4j?

  • Invoking error(exception); will not log the stack trace from exception.
  • Invoking error(“message”,exception); will log the stack trace.

If you’re only using error(), info(), warn(), and debug() to perform logging you’re missing out on a lot of valuable tools; take a moment to browse the Log4j API documentation for Category for details.

Here’s a simple application that illustrates this point…


package net.wakka;

import org.apache.log4j.Logger;

public class Log4jTest
{
    private static Logger log = Logger.getLogger(Log4jTest.class);

    public static void main(String[] args)
    {
        log.info("just a string");

        log.info(new Object() { public String toString() {return "wakka";} });

        try
        {
            int x = Integer.parseInt("yellow");
        }
        catch(NumberFormatException e)
        {
            log.error(e);
            log.error("caught a number format exception",e);
        }
    }

}

Console output follows…

[INFO] just a string
[INFO] wakka
[ERROR] java.lang.NumberFormatException: For input string: "yellow"
[ERROR] caught a number format exception
java.lang.NumberFormatException: For input string: "yellow"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
        at java.lang.Integer.parseInt(Integer.java:447)
        at java.lang.Integer.parseInt(Integer.java:497)
        at net.wakka.Log4jTest.main(Log4jTest.java:23)

Category: Java One comment »

One Response to “Logged exception missing stack trace in Log4j?”

  1. placeoweb

    Are saying the java.lang.NumberFormatException isn’t catch by log4j ?


Leave a Reply

CAPTCHA Image



Back to top