Monday, August 23, 2010

Logging inside a web application using log4j

It is always desirable to have a logging feature for the application, especially when it is interacting with a range of external systems. It would help in traceability and troubleshooting and localizing the problem when things go wrong.

The following is the steps you do for enable logging
1. Download log4j-1.2.16.jar from apache web site and put this in your WEB-INF/lib folder

2. In your web.xml ( preferable your first servlet that executes )
   
       
       

        Login
        Login
        Login
    init-param

        param-name
             log4j-properties-location       

       /param-name
      param-value
       WEB-INF/log4j.properties   
      /param-value  
   /init-param

3. Create a simple text file  log4j.properties and place under WEB-INF folder of web application

---
log4j.rootLogger=DEBUG, R
log4j.rootLogger=TRACE, R

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/myapplication.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

---
4. a) Say in Login servlet init() method

        String log4jLocation = config.getInitParameter("log4j-properties-location");
        ServletContext sc = config.getServletContext();

        if (log4jLocation == null)
        {
            System.err.println("*** No log4j-properties-location init param, so initializing log4j with BasicConfigurator");
            BasicConfigurator.configure();
        } else
        {
            String webAppPath = sc.getRealPath("/");
            String log4jProp = webAppPath + log4jLocation;
            File yoMamaYesThisSaysYoMama = new File(log4jProp);
            if (yoMamaYesThisSaysYoMama.exists()) {
                System.out.println("Initializing log4j with: " + log4jProp);
                PropertyConfigurator.configure(log4jProp);
            } else {
                System.err.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator");
                BasicConfigurator.configure();
            }
        }

        mlog.info("LOG4J initialization for CCM User application successful.");   
       
 ...
4. b )
In the servlet class ( in post method or what have you ) and POJO class deployed
At start declare

Logger mlog = Logger.getLogger(some.class);
..
..
// some action

mlog.info("Inside 'Add UC1 ' request processing.");
mlog.trace("Query executed " + ps);
mlog.trace(ackmsg);
mlog.error(ex.getMessage());

5. Run the application perform actions that would generate these logs.
6. Go to TOMCAT installation %HOME% and open myapplication.log in a text editor.

That it ; you have enhanced traceability of your functionailty you coded.

References :
http://www.avajava.com/tutorials/lessons/how-do-i-initialize-log4j-in-a-web-application.html

Followers