Spring Boot - Logging

Lets look at the Logging options for Spring Boot.

If you use starters(spring-boot-starter artifact in pom.xml), Logback is used for logging by default. This is because spring-boot-starter contains spring-boot-starter-logging.

Logging level

The logging levels are ERROR, WARN, INFO, DEBUG, or TRACE. Default is INFO so DEBUG and TRACE logs are not visible.

Controller to test Logging level

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestController
public class LoggingController {
private static final Logger LOG = LoggerFactory.getLogger(LoggingController.class);

// http://localhost:8080/log
@RequestMapping("/log")
public String log() {
LOG.error("This is an error message.");
LOG.warn("This is a warning message.");
LOG.info("This is an info message.");
LOG.debug("This is a debug message.");
LOG.trace("This is a trace message.");
return "foo";
}
}

You can set logging level in application.properties file or using program arguments.

1
logging.level.root=info

or

1
logging.level.root=INFO

we can also pass log level via command line arguments

1
java -jar target/app.jar --logging.level.root=error

Spring Boot also allows you to set the logging level for a specific package in application.properties file.

1
logging.level.org.hibernate=DEBUG

Logback

You can configure logback by adding one of the following files to classpath

  • logback-spring.xml
  • logback.xml

Sample logback.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<!-- set default log level to be INFO -->
<!-- Log Level: ALL < DEBUG < INFO < WARN < ERROR < FATAL -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Log4j

To use Log4j, we need to exclude spring-boot-starter-logging for all dependencies that uses spring-boot-starter-logging. Then add log4j2 dependency

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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-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>

Then add one of the log4j2 files

  • log4j2-spring.xml
  • log4j2.xml

Reference

source code: https://github.com/xinghua24/SpringBootExamples/tree/master/logging