Log processing is a necessary function of a formal project. The log should be able to save the specified log according to the time, type and other elements according to the specified format, so as to facilitate us to observe the program operation and locate the program bugs.

Logback logging framework is recommended in spring boot.

The sample project in this section is available at https://github.com/laolunsi/spring-boot-examples


Slf4j: a unified facade abstraction for various Java logging frameworks.

Java common logging framework: java.util.logging, log4j, logback, commons logging

Logback is a new generation of log framework developed by the author of log4j, which is widely used at present. Spring boot uses logback by default and info level by default

Logback:

Log loading order: logback.xml – > application.properties – > logback-spring.xml


1、 Log level

Log level defined by log4j: debug / Info / warn / error / fatal

Warn, potential error; error, error, may cause the program to exit; fatal, serious error, the program will exit

There are also two special levels: off – highest level, all – lowest level

Log4j only four levels of debug / Info / warn / error are recommended

Log level: error – > warn – > Info – > debug

If the configuration log level is info, the logs of info and above will be output, and the logs lower than info level (debug logs) will not be output.


2、 Spring boot introduces logger

Direct introduction:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
      <version>2.1.11.RELEASE</version>
      <scope>compile</scope>
    </dependency>

Indirect introduction:

Introducing spring boot starter will automatically introduce spring boot starter logging

Introducing spring boot starter web will automatically introduce spring boot starter


3、 Configuring logback through the springboot configuration file

Configure output log to file:

logging:
  File: logback-demo.log output to the project directory

The default is overlay output, that is, the previous log file will not be deleted or the currently used log file will not be emptied each time the project is started, but a new line will be created below.

Log level:logging.level.*: level-name

*It refers to the package name or log name. The log name, such as root, indicates the system log

Level name refers to the log level, commonly used debug / Info / warn / error

For example:

logging:
  level:
    Com.example.logbackdemo: debug specifies that the logs under the package are output at the debug level
    #Root: warn ා the root log is output at warn level, not debug level!! ---It will get stuck!

4、 Customize logback configuration through XML file

The above configuration does save the log to a file, but it is not useful for the actual project.

For example: the log file is very large. The log size generated every day is hundreds of MB. Can a single file handle it? How to save logs by types? What about customizing the log format?

These are all problems.

Fortunately, most log frameworks, including logback, provide the function of configuration file, and the most common one is to use XML file for configuration.

Log framework default profile:

  • Logback:logback-spring.xml, logback-spring.groovy, logback.xml, logback.groovy
  • Log4j:log4j-spring.properties, log4j-spring.xml, log4j.properties, log4j.xml
  • Log4j2:log4j2-spring.xml, log4j2.xml
  • JDK (Java Util Logging):logging.properties

Log loading order: logback.xml – > application.properties – > logback-spring.xml

Under the logback framework:

It is recommended to use logback-spring.xml, or specify the configuration file through logging.config = classpath: xxx.xml in application.

Example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <contextName>logback-spring-demo-dev</contextName>
    <property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n"/>
    <property name="pattern-color" value="%yellow(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %green(%logger{50}) - %highlight(%msg) %n"/>
    <property name="LOG_HOME" value="logs"/>

    <! -- console output -- >
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <! -- console output - with color -- >
    <appender name="CONSOLE-WITH-COLOR" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${pattern-color}</pattern>
        </encoder>
    </appender>

    <! -- file output -- >
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/all.%d.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>


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

    <logger name="com.example.logbackdemo.IndexAction" level="info" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

</configuration>

The configuration items in logback.xml are described as follows:

There are two attributes and three nodes:

  1. Two properties: contextname and property
  2. Three nodes: appender, root, logger

4.1 contextname property

Contextname: log name, which can be referenced by% contextname

If logback.xml and logback-spring.xml exist at the same time, or logback.xml and customized configuration file exist at the same time, logback.xml will be loaded first, then the specified configuration file will be loaded according to the application configuration, or logback spring and XML will be loaded. If the contextnames of the two configuration files are different, an error will be reported:

ERROR in ch.qos.logback.classic.joran.action.ContextNameAction - Failed to rename context [logback-demo] as [logback-spring-demo-dev] java.lang.IllegalStateException: Context has been already given a name

4.2 property property

The property tag can be used to customize properties, such as defining a < property name = “log_home” value = “logs” / >, and then using ${log_home} to reference it


4.3 appender node

Appender means appender, which can be understood as a log renderer. For example, the rendering console log is in one format, and the rendering file log is in another format.

In the appender, there are two attributes: name and class, and two child nodes: rollingpolicy and encoder.

Name represents the name of the renderer, class represents the output strategy used, and common output strategies include console output strategy and file output strategy.

4.3.1 console output appender

<property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n"/>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <pattern>${pattern}</pattern>
  </encoder>
</appender>

Encoder represents the output format, which is described as follows:

%D for time

%Thread indicates the thread name

%-5level indicates the log level, which allows output in five characters

%Logger {50} indicates the specific log exporter, such as class name, and the length in parentheses

%MSG indicates the specific log message, which is XXX in logger.info (“XXX”)

%N for newline

You can also define color highlighting. For example, pattern is defined as follows:

<property name="pattern-color" value="%yellow(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %green(%logger{50}) - %highlight(%msg) %n"/>

That is to say, you can use% color (xxx) to specify the output color of the corresponding column to highlight the console output color.

4.3.2 file input appender

File output mainly includes configuration: output the log to the file under the specified folder in the specified format, and you can configure the file name, maximum size, and save time

For example:

<property name="LOG_HOME" value="logs"/>
<property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n"/>

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    <fileNamePattern>${LOG_HOME}/all.%d.%i.log</fileNamePattern>
    <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>10MB</maxFileSize>
    </timeBasedFileNamingAndTriggeringPolicy>
    <maxHistory>30</maxHistory>
  </rollingPolicy>

  <encoder>
    <pattern>${pattern}</pattern>
    </encoder>
</appender>

The main content of the above configuration is: output the log to the file under the logs file in the specified format. The file name format is specified as logs / all. Date. Index number. Log. The maximum size of the log file is 10MB. If it is exceeded, a new file will be created. The log file will be kept for 30 days

Index is incremented from 0

Rolling policy refers to the rough rolling. The specific configuration is as above.

The log file size limit can also be configured with < totalsizecap > 1GB < / totalsizecap >.


4.4 root node – enable configuration

The root node is actually to configure which Appenders are enabled, and multiple Appenders can be added.

For example:

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

Indicates that level is info level, and enables the renderer control-with-color and file.

According to this configuration, when the log is output, the console will output it in the format defined by console, and the log file will output it in the configuration of console-with-color.


4.5 logger node

Add configuration to a single package or class:

<! -- the logger node can specify the log configuration of a specific package or class -- >
    <! -- the name property is required, specifies the package or class to be configured, and the level and additivity are optional, with default values -- >
    <! -- level indicates the log level, where the info level is configured, indicating that the logs of info and above are output -- >
    <! -- additivity indicates whether the log is delivered to the previous level. The default value is true -- >
    <logger name="com.example.logbackdemo.IndexAction" level="info" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

Here we add a test interface class:

@RestController
@RequestMapping(value = "log")
public class IndexAction {

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

    @GetMapping(value = "")
    public String testLoggerTag() {
        Logger.debug ("test logger label");
        Logger.info ("test logger label");
        Logger.warn ("test logger label");
        Logger.error ("test logger label");
        return "this is spring-boot-logback-demo projects.";
    }
}

Start the project and call the interface to test:
Logback of spring boot log processing

It is found that the console log output of indexaction class is colorless, that is, the logger configuration takes effect. When additivity is set to true, the console outputs the same content twice.
Logback of spring boot log processing

In addition, there is a springprofile label for specifying the log configuration corresponding to the springboot configuration file. Its application will be discussed below.


4.6 specify which log configurations are enabled

  1. Springboot specifies which XML to enable

    In the configuration file of springboot, we can indicate which XML is used as the logger configuration, for example: logging. Config = classpath: logback spring dev.xml.

    If not specified, the default configuration will be found in the order of logback.xml – > application.yml – > logback-spring.xml.

  2. Using the spring profile tag in XML to specify which configurations should be used in which environments

    We can also specify which configurations are used in which environments in the specific log configuration XML file, such as:

    <springProfile name="local,dev">
        <root level="INFO">
            <appender-ref ref="CONSOLE-WITH-COLOR"/>
            <appender-ref ref="FILE"/>
        </root>
    </springProfile>
    
    <springProfile name="prod">
        <root level="INFO">
            <appender-ref ref="CONSOLE-WITH-COLOR"/>
            <appender-ref ref="FILE"/>
        </root>
    </springProfile>
    

In this way, you don’t need to suggest multiple XML files, just use a default logback-spring.xml.


Reference resources:

https://mrbird.cc/Spring-Boot…

https://www.jianshu.com/p/b3d…

https://blog.csdn.net/lchq199…

https://blog.csdn.net/Rogger_…


Communication learning

Personal website: http://www.eknown.cn

GitHub:https://github.com/laolunsi

Official account:Apes“Sharing technology and understanding life”, welcome to pay attention!
Logback of spring boot log processing