Log4j configuration web application

Log4j configuration web application

To configure log4j with web application and log message either on file or console.

Note: If you add both log4j.propertites and log4j.xml in class path then log4j.xml takes preference over properties file. Use only one file either log4j.propertites or  log4j.xml. In this example we have included both for demo purpose. 

Steps:

  • Create maven project name: Log4jWithWebApplication in your eclipse workspace.
  • Final project structure will look as below:

Log4j configuration web application

Please note: In this web application for demo purpose to log message on console we are using LoggerDemoServlet.java. It’s up to you and your requirement you could use it in any class.

  • pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javahonk</groupId>
    <artifactId>Log4jWithWebApplication</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Log4jWithWebApplication Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <log4j.version>1.2.16</log4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>Log4jWithWebApplication</finalName>
    </build>
</project>

  • log4j.properties:
# rootLogger options
log4j.rootLogger= debug,stdout,file
 
# Write message to log file using RollingFileAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:/JavaHonk/SpringMVCLog4j.log
log4j.appender.file.MaxFileSize=2MB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
# Log on console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
  • log4j.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n" />
        </layout>
    </appender>
    
    <appender name="fileAppend" class="org.apache.log4j.RollingFileAppender">
        <param name="Threshold" value="debug" />
        <param name="File" value="C:/JavaHonk/Log4jXML.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
        </layout>
    </appender>

    <logger name="com.javahonk.servlet.LoggerDemoServlet" additivity="false">
        <level value="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="fileAppend" />
    </logger>
    
    <root>
        <priority value="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="fileAppend" />
    </root>

</log4j:configuration>
  • LoggerDemoServlet.java:
package com.javahonk.servlet;

import java.io.IOException;

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

import org.apache.log4j.Logger;

/**
 * Servlet implementation class LoggerDemoServlet
 */
public class LoggerDemoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger
            .getLogger(LoggerDemoServlet.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoggerDemoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {

        logger.info("Log4j info is working");
        logger.warn("Log4j warn is working");
        logger.debug("Log4j debug is working");
        logger.error("Log4j error is working");
        System.out.println("System out is working");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {
        // TODO Auto-generated method stub
    }

}

  • 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" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <servlet>
    <servlet-name>LoggerDemoServlet</servlet-name>
    <display-name>LoggerDemoServlet</display-name>
    <description>LoggerDemoServlet</description>
    <servlet-class>com.javahonk.servlet.LoggerDemoServlet</servlet-class>   
  </servlet>
  
  <servlet-mapping>
    <servlet-name>LoggerDemoServlet</servlet-name>
    <url-pattern>/LoggerDemoServlet</url-pattern>
  </servlet-mapping>
  
</web-app>

  • index.jsp:
<html>
<body>
<h2>Log4j configuration with Web application</h2>
</body>
</html>

Log4j configuration web application

  • Now execute servlet with its name as below then you will see log on console including file created in C: drive:

Log4j configuration web application

  • C:\JavaHonk\Log4jXML.txt

Log4j configuration web application

 

  • For details explanation of log4j please read this

download Download Project: Log4jWithWebApplication

Leave a Reply

Your email address will not be published. Required fields are marked *