Basic configuration of Log4j in Spring using a .xml file

There are 2 ways to configure Log4j in Spring using:

  • a .properties file
  • a .xml file

The configuration with the. xml file allows to take advantage of some aspects that can not be configured with the .properties file that is therefore regarded as obsolete.
This article will explain how to configure Log4j using the .xml file and the configuration with .properties file was treated in a previous article.
The tools used for the development of this application are:

  • Java 1.6.0_22
  • Tomcat 6.0.20
  • Spring 3.0.4
  • Log4j 1.2.15
  • NetBeans 6.9
    1. Create a NetBeans project or in other IDE called HelloWorld (you can reuse the same project of a previous article)

 

    1. Add the following libraries in the directory /WEB-INF/lib:
      • commons-logging.jar
      • log4j-1.2.15.jar
      • org.springframework.aop-3.0.4.RELEASE.jar
      • org.springframework.asm-3.0.4.RELEASE.jar
      • org.springframework.aspects-3.0.4.RELEASE.jar
      • org.springframework.beans-3.0.4.RELEASE.jar
      • org.springframework.context-3.0.4.RELEASE.jar
      • org.springframework.context.support-3.0.4.RELEASE.jar
      • org.springframework.core-3.0.4.RELEASE.jar
      • org.springframework.expression-3.0.4.RELEASE.jar
      • org.springframework.instrument-3.0.4.RELEASE.jar
      • org.springframework.instrument.tomcat-3.0.4.RELEASE.jar
      • org.springframework.jdbc-3.0.4.RELEASE.jar
      • org.springframework.jms-3.0.4.RELEASE.jar
      • org.springframework.orm-3.0.4.RELEASE.jar
      • org.springframework.oxm-3.0.4.RELEASE.jar
      • org.springframework.test-3.0.4.RELEASE.jar
      • org.springframework.transaction-3.0.4.RELEASE.jar
      • org.springframework.web-3.0.4.RELEASE.jar
      • org.springframework.web.portlet-3.0.4.RELEASE.jar
      • org.springframework.web.servlet-3.0.4.RELEASE.jar
      • org.springframework.web.struts-3.0.4.RELEASE.jar

 

    1. Create the file /WEB-INF/web.xml
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      
          <display-name>HelloWorld</display-name>
      
          <context-param>
              <param-name>log4jConfigLocation</param-name>
              <param-value>/WEB-INF/classes/log4j-helloworld.xml</param-value>
          </context-param>
      
          <listener>
              <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
          </listener>
      
          <servlet>
              <servlet-name>HelloWorld</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <load-on-startup>1</load-on-startup>
          </servlet>
          <servlet-mapping>
              <servlet-name>HelloWorld</servlet-name>
              <url-pattern>*.html</url-pattern>
          </servlet-mapping>
      
          <session-config>
              <session-timeout>
                  30
              </session-timeout>
          </session-config>
          
          <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
          </welcome-file-list>
      
      </web-app>
      

      The specific section about LogjJ is contained in the tags context-param and listener.
      In the context-param tag you define the path to the .xml file to configure Log4j; if you use the standard name log4j.xml, the context-param tag would be unnecessary.

 

    1. Create the file /WEB-INF/HelloWorld-servlet.xml
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
      	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
      	xmlns:context="http://www.springframework.org/schema/context"
      	xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-3.0.xsd">
          <context:component-scan base-package="it.helloworld.controller" />
      
          <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix">
                  <value>/WEB-INF/views/</value>
              </property>
              <property name="suffix">
                  <value>.jsp</value>
              </property>
          </bean>
      
      </beans>
      

 

    1. Create the file /WEB-INF/classes/log4j-helloworld.xml
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
      <log4j:configuration>
          <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
              <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" />
      <!--
      ConversionPattern format specification
      %d      inserts the date; you can specify the format (%d{yyyy-MM-dd HH:mm:ss,SSS})
      %-5p    inserts the priority log level, 5 characters, left justified
      %c{1}   inserts the name of the class
      %L      inserts the line number
      %m      inserts the user message
      %n      inserts the separator (for example, a new line)
      -->
              </layout>
          </appender>
      
          <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
              <param name="Threshold" value="INFO" />
              <param name="MaxFileSize" value="512KB" />
              <param name="MaxBackupIndex" value="10" />
              <param name="File" value="${webapp.root}/WEB-INF/logs/helloworld.log"/>
              <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" />
              </layout>
          </appender>
      
      <!--sets the priority log level for org.springframework-->
          <logger name="org.springframework">
              <level value="info"/>
          </logger>
      
      <!--sets the priority log level for it.helloworld.controller-->
          <logger name= "it.helloworld.controller">
              <level value="debug"/>
          </logger>
      
      <!--sets the default priority log level-->
          <root>
              <priority value="info"></priority>
              <appender-ref ref="stdout"/>
              <appender-ref ref="fileAppender"/>
          </root>
      </log4j:configuration>
      

      In this example I used the variable webapp.root but you can use others like catalina.home.

 

    1. Create the file index.jsp in the root of the application
      <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
      
      <html>
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>Welcome Page</title>
          </head>
          <body>
              <jsp:forward page="helloWorld.html" />
          </body>
      </html>
      

 

    1. Create the directory /WEB-INF/views and the file /WEB-INF/views/helloWorld.jsp
      <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
      
      <html>
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>JSP Page</title>
          </head>
          <body>
              <h1>Hello World!</h1>
          </body>
      </html>
      

 

    1. Create the file /WEB-INF/classes/it/helloworld/controller/HelloWorldController.java
      package it.helloworld.controller;
      
      import org.apache.log4j.Logger;
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.servlet.ModelAndView;
      
      @Controller
      public class HelloWorldController {
      
          private static org.apache.log4j.Logger log = Logger.getLogger(HelloWorldController.class);
      
          @RequestMapping(value = {"/index", "/helloWorld"})
          public ModelAndView helloWorld() {
      
              log.trace("Trace");
              log.debug("Debug");
              log.info("Info");
              log.warn("Warn");
              log.error("Error");
              log.fatal("Fatal");
      
              return new ModelAndView("helloWorld");
          }
      }
      

 

  1. Deploy and launch the application and verify the log in the console and in the file ${webapp.root}/WEB-INF/logs/helloworld.log


Comments

4 responses to “Basic configuration of Log4j in Spring using a .xml file”

  1. Gabriele Avatar

    Salve,
    complimenti per il tutorial. Veramente molto utile e chiaro! Volevo segnalare solo una cosetta che manda un po in confusione. Tra le prime righe si trova questa frase:
    “In questo articolo spiegherò come configurare Log4j usando il file .xml mentre la configurazione con il file .xml è stata trattata in un precedente articolo.”

    penso sia una piccola distrazione ma secondo me dovrebbe essere

    “In questo articolo spiegherò come configurare Log4j usando il file .xml mentre la configurazione con il file .properties è stata trattata in un precedente articolo.”

    🙂 solamente per essere pignoli ^^

    buona giornata
    thanks for share

    1. Grazie, ho corretto il post.

  2. Cesar Pastor Avatar
    Cesar Pastor

    SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.util.Log4jConfigListener
    java.lang.NoClassDefFoundError: org/apache/log4j/LogManager
    at org.springframework.util.Log4jConfigurer.shutdownLogging(Log4jConfigurer.java:116)
    at org.springframework.web.util.Log4jWebConfigurer.shutdownLogging(Log4jWebConfigurer.java:170)
    at org.springframework.web.util.Log4jConfigListener.contextDestroyed(Log4jConfigListener.java:49)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4741)
    at org.apache.catalina.core.StandardContext$4.run(StandardContext.java:5450)
    at java.lang.Thread.run(Unknown Source)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5459)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:225)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:153)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:774)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:620)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:303)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:431)
    Caused by: java.lang.ClassNotFoundException: org.apache.log4j.LogManager
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    … 26 more

    1. Luca Zanini Avatar
      Luca Zanini

      See here
      Maybe you have more log4j*.jar

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.