Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log from Spring MVC

I am trying to log from a controller in Spring MVC but nothing appears. I am using SLF4J with logback. I managed to log from a main class, but after making it a web application it does not log.

I thought it would work since SL4JF and Logback is in the classpath.

@Controller
@RequestMapping(value = "/cars")
public class CarController {

    private Logger logger = LoggerFactory.getLogger(CarController.class);

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> newCar() {
        logger.info("new car");
        // more code
        return map;
    }
}

logback.xml

<configuration scan="true">
    <property name="LOG_DIR" value="/My/User/Desktop"/>

    <!--Loggers-->
    <logger name="my.company" level="DEBUG"/>

    <!--Root logger-->
    <root level="debug">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE_ROLLER"/>
    </root>

    <!--Appenders-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE_ROLLER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/mylog.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>mylog.%d{yyyy-mm-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
</configuration>
like image 614
LuckyLuke Avatar asked Oct 18 '25 06:10

LuckyLuke


1 Answers

This is because Spring is using Java Commons Logging by default. You should put jcl-over-slf4j library in your classpath, in order to Spring use SLF4J for logging.

With maven, use these dependencies in addition to SLF4J+Logback:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${slf4j.version}</version>
    <scope>runtime</scope>
</dependency>
like image 134
jelies Avatar answered Oct 19 '25 22:10

jelies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!