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 log4.properties 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 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 :

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Create log4j.properties

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

Log4j

File : log4j.properties – Define how log4j handling 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=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p] %d %c %x - %m%n

# File Logger
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/oes
log4j.appender.file.DatePattern='-'yyyy-MM-dd'.log'
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p] %d %c %x - %m%n

Use Log4j in Spring MVC

In Controller, you can use Log4j as following:

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;

@Controller
@RequestMapping(value = "/accounts")
public class AccountsController {
    @RequestMapping(value = "/login.action", method = RequestMethod.POST)
    public @ResponseBody HashMap&lt;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&lt;String, Boolean> result = getLoginResult(username, password);
        logger.info(String.format("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;

    @Autowired
    UserService userService;

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

Disable Log4j in Test Environment

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

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.17</version>
    <configuration>
        <systemPropertyVariables>
            <log4j.configuration>file:${project.build.testOutputDirectory}/log4j-silent.properties</log4j.configuration>
        </systemPropertyVariables>
    </configuration>
</plugin>

Then create log4j-silent.properties(DO NOT USE log4j.properties) in TEST classpath.

Contact Us
  • SenseTime Research, Shenzhen Bay Eco-Technology Park
  • cshzxie [at] gmail [dot] com