Monday, 22 October 2012

Setting Logging Dependencies In Spring

This post describes how to set-up logging dependencies in Spring. It is based on information available in a post by Dave Syer. A reminder on Java logging frameworks is available here. The code example is available at GitHub in the Spring-Logging-Dependencies directory.

Spring uses Jakarta Commons Logging API (JCL). Unfortunately, many people do not like its runtime discovery algorithm. We can disactivate it and use SLF4J with Logback instead. We will use a variation of the Spring MVC with Annotations example to do so.

Here is the modified controller:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

public class MyController {

    private static final Logger LOG
        = LoggerFactory.getLogger(MyController.class);

    @RequestMapping(value = "/")
    public String home(Model model) {

        String s = "Logging at: " + System.currentTimeMillis();;

        model.addAttribute("LogMsg", s);

        return "index";


We create a SFL4J logger and log some information with current time in milliseconds.

The maven dependencies are:





Once built, one can start the example by browsing: http://localhost:9393/spring-logging-dependencies/. It will display the following:

Spring Logging Configuration

In the logs, you will find the logged statement:

Spring Logging Statement

More Spring posts here.

No comments:

Post a comment