TechAlpine – The Technology world

Spring and Log4J integration – Let’s explore

Spring & Log4J

Spring Series – Learn Log4J integration by Example


In this short tutorial we will directly jump into the implementation and coding part. We will not discuss much on the theoretical part. This will help the developers to get a quick reference and integrate Log4J easily with Spring framework.

How to configure?

Logger is an important part of any application and the most commonly used logging mechanism is log4j. Spring based applications can also use the power of log4j. Following is a complete example on spring and log4j integration.

  • The first component is the web.xml file which contains the path for properties file.





  • The second part is the file which contains the log level information. It entirely depends upon your application need.

# Log appender for package in.techdive,myAppLog





log4j.appender.myAppLog.layout.ConversionPattern=%d [%c: %L] – %m%n



# Log appender for package org,springLog





log4j.appender.springLog.layout.ConversionPattern=%d [%c: %L] – %m%n



# Log appender for package stdout



log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] – <%m>%n

  • The 3rd part is the java class java to test the log4j configuration. If you run the application the log messages will be displayed.

package com.techalpine;


import java.util.HashMap;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;


* Class for testing Logger.


public class Log4JTest implements Controller


private final Log logger  = LogFactory.getLog(getClass());

public ModelAndView handleRequest(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{“Add message here which are of info type“);

logger.debug(“Add message here which are of debug type“);

return new ModelAndView(“response”, “model”, map);




Now we know how to configure Log4J with Spring framework. The steps are very easy and can be followed quickly. Here we have only discussed and the hands-on coding part so that the developers can implement it easily with a back ground knowledge of Log4J. We have kept the theoretical part aside intentionally to make it simple. Hope you will enjoy it. We will cover the conceptual part more in details in our next posts.

Tagged on: ,

Leave a Reply

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

× 7 = 56

============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------