Reputation: 49097
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>
Upvotes: 4
Views: 15603
Reputation: 907
Exclude the default logger and add whatever logger you want to use in your pom.xml file like as below.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Upvotes: 0
Reputation: 9290
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>
Upvotes: 6