Integrate Spring MVC with Log4j

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 classpath, Done.

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

Add Log4j Library to Your Project

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



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


File : – Define how log4j handles the logged message, in this example, it will redirect all the logged messages into a text.

# LOG4J configuration
log4j.rootLogger=INFO, console, file

# Console Logger
log4j.appender.console.layout.ConversionPattern=[%p] %d %c %x - %m%n

# File Logger
log4j.appender.file.layout.ConversionPattern=[%p] %d %c %x - %m%n

Use Log4j in Spring MVC

In Controller, you can use Log4j as follows:

package edu.hfut.oes.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import edu.hfut.oes.model.User;
import edu.hfut.oes.service.UserService;

@RequestMapping(value = "/accounts")
public class AccountsController {
    @RequestMapping(value = "/login.action", method = RequestMethod.POST)
    public @ResponseBody HashMap<String, Boolean> loginAction(
            @RequestParam(value="username", required=true) String username,
            @RequestParam(value="password", required=true) String password,
            HttpServletRequest request,
            HttpSession session,
            Model model) {
        String ipAddress = request.getRemoteAddr();
        HashMap<String, Boolean> result = getLoginResult(username, password);"User: [Username=%s] tried to log in at %s", new Object[] {username, ipAddress}));
        if ( result.get("isSuccessful") ) {
            getSession(request, session, this.user);
        return result;


    private User user = null;

    UserService userService;

    private Logger logger = Logger.getLogger(AccountsController.class);

Disable Log4j in Test Environment

Add a Plugin called maven-surefire-plugin in pom.xml (If you're using Maven)


Then create as follows

Contact Us
  • Tencent Binhai Building, Shenzhen, China
  • root [at] haozhexie [dot] com