Jay SenSharma

Jay SenSharma

Here is a Simple Sample to use Log4j Logging to log Application Events,debug and info messages. In this sample we are using “log4j-1.2.8.jar” you can download it form “http://findjar.com/index.x“.

We can use either Properties file or an XML file to define the Logger details. In this sample i am using XML file.

Step1). Create a WebApplication TestApp and place the Above Jar (“log4j-1.2.8.jar“) file inside “TestAppWEB-INFlib” directory.

Step2). Develope a Simple Servlet “MyServlet.java” inside “TestAppWEB-INFclasses”

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator; // If u use XML log4j file

public class MyServlet extends HttpServlet
public void service(HttpServletRequest req , HttpServletResponse res)throws ServletException,IOException
java.net.URL url=Thread.currentThread().getContextClassLoader().getResource("MyLog4j.xml");

//NOTE: If u use log4j.properties file then use  PropertyConfigurator

Logger logger = Logger.getLogger(MyServlet.class);
logger.info(" This is an information message");
logger.error("This is an error message");
logger.fatal("This is a fatal error message");

PrintWriter out=res.getWriter();
out.println("<Hr><h1>Please check the Logs Are generated in F:/MyLogs/MyAppLogs.log or Not .....");

Step3). Provide the entry of this Servlet in “web.xml

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">


Step4). Place the “MyLog4j.xml” file inside “TestAppWEB-INFclasses” directory…

<?xml version="1.0" encoding="UTF-8" ?>
   <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
     <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
           <appender name="appender" class="org.apache.log4j.DailyRollingFileAppender">
               <param name="DatePattern" value="'.'yyyy-MM-dd"/>
	       <param name="File" value="/home/jsenshar/DELETE/MyAppLogs.log"/>
	       <param name="Append" value="true"/>
                <layout class="org.apache.log4j.PatternLayout">
	           <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
          <priority value ="debug"/>
          <appender-ref ref="appender"/>

In the Above XMl file Just Change the value of <param name=”File” value=”F:/MyLogs/MyAppLogs.log”/>    Whereever you want to generate the Log Files…

Step5).. compile Servlet and Deploy the WebApplication….

Step6). Now Access your Servlet like :





Jay SenSharma

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.