Springboot unified log processing (Logback)

1. Log introduction

1. What is a log

View the running process of the program, running information, exception information, etc. through the log.
Source code: https://gitee.com/charlinchenlin/store-pos

2. Log function:

1. Quickly locate and troubleshoot problems;
2. Record user information;
3. Record operation information, which can help restore data or locate responsible persons;
4. Record the execution time of the program for easy access to optimization and analysis;

3. Log level

The behavior of Loggers is hierarchical. As shown in the table below:

  • Divided into: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF

By default, the log level printed by spring boot from the console is only INFO and above, and the log level can be configured

# 设置日志级别
logging:
  level:
    root: ERROR

This method can output logs of ERROR level and above to the console, and other levels will not output

Second, create a basic Logback log

1. Create a log file

Spring boot internally uses Logback as the framework for log implementation.
First delete the logback-spring.xml created in the log level configuration resources in application.yml
(the name of the default log file)
insert image description here

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

</configuration>

2. Create test log output

Just output the following logs to any controller method, such as the list method

@ApiOperation("用户列表")
@GetMapping("/list")
public R listAll(){
    
    

    log.info("hi i'm helen");
    log.warn("warning!!!");
    log.error("it's a error");

    List<User> list = userService.list();
    return R.ok().data("list", list);
}

Three, Logback log file analysis

1. configuration attribute

The root node of the log configuration

<configuration></configuration>

2. contextName property

contextName is a child node of configuration.

Each logger is associated with a logger context, and the default context name is "default". But you can use contextName to set other names to distinguish different applications.

<contextName>koopig</contextName>

3. property attribute

property is a child node used to define variables.
property has two attributes, name and value: the value of name is the name of the variable, and value is the value of the variable.
The value defined by the property will be inserted into the logger context. After defining a variable, you can use "${}" to use the variable.

<!-- 日志的输出目录 -->
<property name="log.path" value="D:/project/finance/srb_log/core" />

<!--控制台日志格式:彩色日志-->
<!-- magenta:洋红 -->
<!-- boldMagenta:粗红-->
<!-- cyan:青色 -->
<!-- white:白色 -->
<!-- magenta:洋红 -->
<property name="CONSOLE_LOG_PATTERN"
          value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>

<!--文件日志格式-->
<property name="FILE_LOG_PATTERN"
          value="%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n" />

<!--编码-->
<property name="ENCODING"
          value="UTF-8" />

4. appender property

Appender is a sub-node of configuration and is the component responsible for writing logs.
Appender has two necessary attributes name and class: name specifies the name of the appender, class specifies the fully qualified name of the appender
encoder formats the log
pattern defines the specific output format of
the log charset encoding Way

Console log configuration

<!-- 控制台日志 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        <charset>${ENCODING}</charset>
    </encoder>
</appender>

file log configuration

file indicates the location of the log file. If the upper-level directory does not exist, it will be created automatically, and there is no default value.
append defaults to true, and the log is appended to the end of the file. If it is false, the existing file will be cleared after the service restarts.

<!-- 文件日志 -->
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${log.path}/log.log</file>
    <append>true</append>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
        <charset>${ENCODING}</charset>
    </encoder>
</appender>

5. logger attribute

logger can be a child node of configuration, which is used to set the log printing level of a certain package or a specific class, and specify appender
name: used to specify a certain package or a specific class that is constrained by this logger
level: used to set Printing level, case insensitive: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF. By default, the level logger that inherits from the parent
can contain zero or more appender-ref elements, indicating that this appender will be added to this logger

<!-- 日志记录器  -->
<logger name="com.koo" level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="FILE" />
</logger>

4. Multi-environment configuration

In a project developed based on Spring boot, it is often necessary to configure multiple sets of environments: development, testing and production. Different environments such as development (dev), testing (test) and production (prod) can be configured separately using springProfile

<!-- 开发环境和测试环境 -->
<springProfile name="dev,test">
    <logger name="com.koo" level="INFO">
        <appender-ref ref="CONSOLE" />
    </logger>
</springProfile>

<!-- 生产环境 -->
<springProfile name="prod">
    <logger name="com.koo" level="ERROR">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </logger>
</springProfile>

Five, rolling log configuration

Problem: In a production environment, if the system runs for a long time, the log file will become larger and larger, and the time for the system to read and write the log will become slower and slower. In severe cases, the system memory will be exhausted, causing the system to crash. machine.

Solution: A rolling log can be set.

1. Set the time rolling strategy

  • RollingFileAppender is another implementation of Appender, which means rolling record files, first record the log to the specified file, and when a certain condition is met, back up the old log to other files
  • rollingPolicy is a child node of appender, which is used to define the rolling policy.
  • TimeBasedRollingPolicy: The most commonly used rolling policy, formulating a rolling policy based on time.
  • fileNamePattern: contains the file name and conversion character, "%d" can contain the specified time format, such as: %d{yyyy-MM-dd}. If %d is used directly, the default format is yyyy-MM-dd.
  • maxHistory: Optional node, controls the maximum number of archive files to keep, and deletes old files if the number exceeds. Assuming that it is set to roll every month, and maxHistory> is 6, only the files of the last 6 months will be saved, and the old files before will be deleted. Note that when deleting old files, the directories created for archiving are also deleted.
<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

    <!--  要区别于其他的appender中的文件名字  -->
    <file>${log.path}/log-rolling.log</file>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
        <charset>${ENCODING}</charset>
    </encoder>


    <!-- 设置滚动日志记录的滚动策略 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- 日志归档路径以及格式 -->
        <fileNamePattern>${log.path}/info/log-rolling-%d{
    
    yyyy-MM-dd}.log</fileNamePattern>
        <!--归档日志文件保留的最大数量-->
        <maxHistory>15</maxHistory>
    </rollingPolicy>

</appender>

2. Set the timing of trigger scrolling

  • Put it at the position of the child node of <rollingPolicy>, trigger the rolling policy based on the actual policy
  • <maxFileSize> Set the trigger rollover condition: generate a new file when a single file is larger than 100M
  • Note: modify the log file name at this time <fileNamePattern> ${log.path}/info/log-rolling-%d{yyyy-MM-dd}.%i.log </fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>1KB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>

6. Complete log configuration file

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <contextName>koopig</contextName>

    <!-- 日志的输出目录 -->
    <property name="log.path" value="D:/project/test/core" />

    <!--控制台日志格式:彩色日志-->
    <!-- magenta:洋红 -->
    <!-- boldMagenta:粗红-->
    <!-- cyan:青色 -->
    <!-- white:白色 -->
    <!-- magenta:洋红 -->
    <property name="CONSOLE_LOG_PATTERN"
              value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>

    <!--文件日志格式-->
    <property name="FILE_LOG_PATTERN"
              value="%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n" />

    <!--编码-->
    <property name="ENCODING"
              value="UTF-8" />

    <!-- 控制台日志 -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>${ENCODING}</charset>
        </encoder>
    </appender>

    <!-- 文件日志 -->
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${log.path}/log.log</file>
        <append>true</append>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>${ENCODING}</charset>
        </encoder>
    </appender>

    <appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

        <!--  要区别于其他的appender中的文件名字  -->
        <file>${log.path}/log-rolling.log</file>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>${ENCODING}</charset>
        </encoder>


        <!-- 设置滚动日志记录的滚动策略 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 日志归档路径以及格式 -->
            <fileNamePattern>${log.path}/info/log-rolling-%d{
    
    yyyy-MM-dd}.%i.log</fileNamePattern>
            <!--归档日志文件保留的最大数量-->
            <maxHistory>15</maxHistory>

            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>1KB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>

    </appender>


    <!--    <logger name="com.koo" level="INFO">-->
    <!--        <appender-ref ref="CONSOLE" />-->
    <!--        <appender-ref ref="FILE" />-->
    <!--    </logger>-->

    <!-- 开发环境和测试环境 -->
    <springProfile name="dev,test">
        <logger name="com.koo" level="INFO">
            <appender-ref ref="CONSOLE" />
        </logger>
    </springProfile>

    <!-- 生产环境 -->
    <springProfile name="prod">
        <logger name="com.koo" level="ERROR">
            <appender-ref ref="CONSOLE" />
            <appender-ref ref="ROLLING_FILE" />
        </logger>
    </springProfile>
</configuration>

Seven, please see the source code for details

https://gitee.com/charlinchenlin/store-pos

Guess you like

Origin blog.csdn.net/lovoo/article/details/130020906