javaerror-handlinglog4jstack-traceexception-logging

Is it possible to print extra custom fileds along with the StackTrace while using log4j


I have this program as shown below , right now its only printng the stacktrace . my question is that , is it possible to get the stack trace and also a custom field , here in my case i need 1090099

Please tell me if its possible ??

package com;
import org.apache.log4j.Logger;
public class Test {

    private static final Logger logger = Logger.getLogger(Test.class);
    public static void main(String args[]) {
        try {
    String accountid = "1090099";
            String desc = null;
            System.out.println(desc.toUpperCase());
            } 
            catch (Exception t) 
        {
            logger.fatal("Exception inside the Test program  ", t);
        }
    }
}

2013-06-26 21:44:29,723[main] FATAL(Test.java:<main>:16)- Exception inside the Test program
java.lang.NullPointerException
    at com.Test.main(Test.java:12)

Solution

  • Yes, you can print the value as long as it's in scope.

    String accountid = null;
    try {
         accountid = "1090099";
         String desc = null;
         System.out.println(desc.toUpperCase());
     } catch (Exception t) {
         logger.fatal("Exception inside the Test program  " + accountid, t);
     } 
    

    Also, I would suggest using logger.debug instead of system.out.println for your other logging calls...