It’s quite straightforward to integrate Log4j into the Spring MVC application. First, include Log4j.jar library into your project dependency, then create a file to define the Log4j’s appender and put this file into the project class path, Done.

In tutorial, we show you how to integrate the Log4j logging framework into the Spring MVC application.

1. Log4j library

Download the Log4j library from the official website, or via Maven :

        <!-- Log4j -->


Create a Log4j properties file (, put it into the project class path. see figure :


File : – Define how log4j handling the logged message, in this example, it will redirect all the logged messages into a text file named “C:\\loging.log“.

# Direct log messages to a log file
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=debug, file, stdout

3. Spring MVC + Log4j

In Java class, call Logger.getLogger to return the Log4j handler to handle the logging task.

package com.mkyong.common.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
        //get log4j handler
	private static final Logger logger = Logger.getLogger(WelcomeController.class);
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		ModelAndView model = new ModelAndView("WelcomePage");
		model.addObject("msg", "Hello ~ Log4j");
		//log it via log4j
		return model;


Run the application, when you access the WelcomeController class, it will log the “ModelAndView” object into the c:\\logging.log file.

15:01:51,682 DEBUG WelcomeController:23 - 
ModelAndView: reference to view with name 'WelcomePage'; model is {msg=Hello ~ Log4j}
15:01:51,688 DEBUG InternalResourceViewResolver:81 - Cached view [WelcomePage]

Download Source Code


  1. Log4j Official Website
Tags :
Founder of, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to the charity, thanks.

Related Posts

Popular Posts