Sunday, August 12, 2012

Log4j Tutorial : Configure Log4j In a web application

Step 1: create your web application in eclipse
Step 2: Create web.xml as fallows

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>CMIS_NEW</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
   
   
  <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>/WEB-INF/log4j.properties</param-value>
 </context-param>
  
  <servlet>
  <servlet-name>TestLog4j</servlet-name>
  <servlet-class>com.cims.TestLog4jServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
   <servlet-name>TestLog4j</servlet-name>
   <url-pattern>/test</url-pattern>
  </servlet-mapping>
  
  
  
</web-app>

Step 3: Create servlet which initialized your log4j configuration
package com.cims;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;

public class Log4JServlet extends HttpServlet {
 
 public void init() throws ServletException{
  
  String log4jfile = getInitParameter("log4j-init-file");
  if(log4jfile != null){
   String propfile = getServletContext().getRealPath(log4jfile);
   PropertyConfigurator.configure(propfile);
  }
  
 }

}

Step 4: Create log4j.properties and place into the classpath
log4j.rootLogger=INFO, CMISAppender
log4j.appender.CMISAppender=org.apache.log4j.ConsoleAppender
log4j.appender.CMISAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.CMISAppender.layout.ConversionPattern=%-4r [%t] %-5p %d %c %x - %m%n

Step 5: Create your tester servlet as fallows
package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


public class TestLog4jServlet extends HttpServlet {
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 static Logger logger = Logger.getLogger(TestLog4jServlet.class);
 
 public void doGet(HttpServletRequest req,HttpServletResponse res) 
   throws ServletException,IOException{
  logger.info("Starting the "+this.getClass().getName()+" doGet() Method");
  res.setContentType("text/html");
  PrintWriter out = res.getWriter();
  out.println("Log4j Debugger Example");
  logger.info("Exiting the "+this.getClass().getName()+" doGet() Method");
  
 }

}





No comments: