Friday, August 23, 2013

How to configure log4j in CometD application


Logging is the most important part of an application because it helps developer a lot in getting the insight of any module or a block of code. Here we are going to use log4j for logging purpose. Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License. It is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.

It has 3 main components:

1.       loggers: These are responsible for capturing the logging information from specified package or file name as mentioned under “name” attribute. It also specifies the log level like info, debug etc and list of references of appenders that will display the logging informations.

2.       appenders: It is responsible for displaying the logging information at various destinations like console, log files etc. it also defines the pattern for showing logs under “layout” tags.

3.       layouts: It formats logging information according to our style and it is defined under appenders.

These tags are defined in log4j.xml file.

Steps to configure logs in cometd applications:

Step 1) Download jars: Following jars are needed for logging in cometd application like:

log4j-1.2.15.jar,
slf4j-api-1.6.4.jar,
slf4j-log4j12-1.6.4.jar

Step 2) Create log4j.xml: Create log4j.xml file that will have all logging informations like loggers, appenders, layouts etc as given below. Place this file in WEB-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "dtd/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 
  <appender name="aa" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="c:/JKLOG/aa-log.log" />
    <param name="MaxFileSize" value="5120KB" />
    <param name="MaxBackupIndex" value="30" />
    <param name="Append" value="true" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p] [%x]  @ %C{1} : %M : %L - %m%n" />
    </layout>
  </appender>
 
  <appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p] [%x]  @ %C{1}: %M : %L - %m%n"/>
    </layout>
  </appender>
 
 
  <root>
    <level value="warn"/>
    <appender-ref ref="aa" />
  </root>
 
   <logger name="com.test.ai.amap.gsontest.MyService">
        <level value="info" />
        <appender-ref ref="console" />
        <appender-ref ref="aa" /> 
       
  </logger>
 
  <logger name="org.cometd.server">
        <level value="all" />
        <appender-ref ref="console" />
        <appender-ref ref="aa" /> 
       
  </logger>
 
</log4j:configuration>

Step 3) Configure log4j.xml and test your applications: To configure and use log4j.xml file, we have to do two things.
  •  we have to create an instance of Logger class and that instance will be used to print out custom logs as private static final Logger _log = LogManager.getLogger(MyService.class);
  • We have to use “DOMConfigurator.configure("C:/workspace/POC/CometDIdea/WebContent/WEB-INF/log4j.xml");” to load the log4j.xml file and use it. Generally this is done in some servlet class in such a way that these code run only on time. I have done it in my service class.


package com.test.ai.amap.gsontest;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.cometd.bayeux.server.ConfigurableServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.java.annotation.Configure;
import org.cometd.java.annotation.Listener;
import org.cometd.java.annotation.Service;
import org.cometd.server.authorizer.GrantAuthorizer;


@Service
public class MyService
{
      @org.cometd.java.annotation.Session
    private ServerSession _session;
      private static final Logger _log = LogManager.getLogger(MyService.class);
     
      public MyService(){          
            DOMConfigurator.configure("C:/workspace/POC/CometDIdea/WebContent/WEB-INF/log4j.xml");
      }
     
      @Configure("/service/*")
    public void configureExecuteCommand(ConfigurableServerChannel channel)
    {
      channel.addAuthorizer(GrantAuthorizer.GRANT_SUBSCRIBE_PUBLISH);
      channel.setPersistent(true);
    }
   
    @Listener("/service/foo")
    public void handleFooMessages(ServerSession remote, ServerMessage message)
    {
      System.out.println("---------------------Hello World---------------------------");
      _log.info("*************This is hello world logging from MyService.java***************");
      remote.deliver(_session, message.getChannel(),"I am Saying Hello World From Server", null);
    }
}


Note: It has been advised in CometD doc to use flag “logLevel” in web.xml so that it can control the log level. But, I found that its not working. The log level is controlled by <level value=" " /> tag under <logger> tag in log4j.xml file. If any one finds the way of using “logLevel”, please post your comment here. It will be helpful for us.

No comments:

Post a Comment

Please provide your precious comments and suggestion