Use Logback to output logs in SpringBoot applications

Use Logback to output logs in SpringBoot applications

Logs are very important for development. Effective output of logs can greatly help locate problems, especially online problems.

1 SpringBoot's support for Logback

SpringBoot support Java Util Logging, Log4J2, Logbackand other logging implementation. By default, it is used Logback. Therefore, during development, it can be easily integrated Logback, and SpringBoot provides some default configurations, which can easily output the log to the console or file.

Use Starter[spring-boot-starter-web] to create a SpringBoot application, create a maven project, pom.xmland add dependencies in it:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0        http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spingboot.one</groupId>
    <artifactId>logback-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
 

Then, create a package com.springboot.one, and create the main class under the packageApplication.java

package com.springboot.one;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 

After startup, you can see the output log in the console:

2018-08-15 22:26:08.731  INFO 3820 --- [           main] com.springboot.one.Application           : No active profile set, falling back to default profiles: default
2018-08-15 22:26:09.119  INFO 3820 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1b083826: startup date [Wed Aug 15 22:26:09 CST 2018]; root of context hierarchy
2018-08-15 22:26:12.792  INFO 3820 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-08-15 22:26:12.830  INFO 3820 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
 

Above, you can clearly see the log time, level, thread and other information.

2 Configure Logback

In SpringBoot applications, there are two ways to configure logs:

  1. In application.propertiesconfigured in
  2. Use a separate logback configuration file

Both of these two methods can configure Logback. Both methods have their own advantages and disadvantages. However, in actual development, it is recommended to use the second method for configuration. The main advantages are as follows:

  • Separated from other configurations, log configuration is concentrated in this file
  • More flexible configuration

2.1 Output the log to the console

Next, in the project, add a separate logback configuration file:, logbackd-emo\src\main\resources\logback-spring.xmlpay attention to the name of the configuration file logback-spring.xml, follow this convention, SpringBoot will load the configuration file by default.

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

    <root level="DEBUG">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>
 

Above, through the configuration to output the log to the console, adjust the log level to DEBUG level, here is a direct reference to the built-in configuration file of SpringBoot, of course, this can also be reconfigured according to your own needs.

2.2 Output log to file

You can also output the log to a specified file, where you can directly refer to the built-in configuration file of SpringBoot:

<include resource="org/springframework/boot/logging/logback/file-appender.xml"/>
 

However, this configuration file function is too simple. Usually, it will be customized in the project, for example, like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">

    <property name="LOG_HOME" value="${user.dir}/logs/"/>
    <property name="APP_NAME" value="app-server"/>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP_NAME}-%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="FILE"/>
    </root>

    <logger name="org.springframework.data.mongodb.core.MongoTemplate" level="debug"/>
    <logger name="org.springframework.data.repository.config" level="WARN"/>

</configuration>

 

To output the log to a file, more content needs to be considered:

  • The path of the log file may require a separate partition in a production environment.
  • The naming rules of log files, using date naming can be easily searched.
  • The log rolling strategy, if the log volume is not large, the log can be cut on a daily basis.

At the same time, some log levels have been adjusted in this configuration to reduce useless logs, which is very important for locating problems.

3 Load log configuration according to the environment

The above content is basically the related configuration of Logback. SpringBoot has also made some special extensions to the log configuration. Among them, there is a feature that is particularly useful, which is to support the Profile feature in the log configuration, which can be easily realized through the Profile. Environment load log configuration.

For example, there are currently three environments with different log output requirements:

  • Production environment: output to file
  • Development environment: output to the console
  • Test environment: output to file

Now you can configure it like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <property name="LOG_FILE" value="${user.dir}/logs/app.log}"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
    <include resource="org/springframework/boot/logging/logback/file-appender.xml"/>

    <springProfile name="dev">
        <root level="DEBUG">
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

    <springProfile name="prod, test">
        <root level="DEBUG">
            <appender-ref ref="FILE"/>
        </root>
    </springProfile>

</configuration>
 

Then, application.propertiesconfigure the profile in:

spring.profiles.active=prod
 

At this point, it is running in a production environment, and the log will be output to a file.

4 summary

This article mainly introduces how to use Logback to output logs in SpringBoot, and also introduces a practical trick, that is, how to load log configuration according to the environment. However, in actual development, these are far from enough, and there are still many problems to be solved, such as:

  1. How to collect logs from multiple servers
  2. How to store logs effectively
  3. How to query logs conveniently and efficiently

In the future, we will continue to introduce more log collection schemes. follow me: