How does Spring Boot handle logs?

Hi! Hello, everyone. Today I'll teach you how to configure logs in the Spring Boot project. What's the use of logs? Of course, it is to record the system operation records, which is convenient for us to troubleshoot and observe the system operation status. In production practice, log processing is a very important part.

Log level

Common log levels from low to high are: trace < debug < info < warn < error < fatal

If the log you set is basically INFO, the logs below it will not be displayed / recorded, such as TRACE and DEBUG, and so on.

Common logging frameworks

  • log4j
    A Java based logging tool, it is said that the official is no longer updated. Later, the Log4j team created a new version of Log4j with version number 2.0. That is log4j2.
  • log4j2
    Log4j2 is an upgrade of log4j, which is 1.5% higher than its predecessor log4j X provides significant improvements. In 2021, a loophole was discovered and was repaired urgently.
  • logback
    Logback is another open source logging component designed by the founder of log4j. Compared with log4j, its performance is improved by more than 10. It is also the default logging framework of Spring Boot.

Log framework of Spring Boot

The default logging framework of Spring Boot is logback, so there is no need to reintroduce the dependency of logback in Spring Boot projects.

How do I print logs in a project?

Introducing Lombok dependency

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Then mark a comment on the class @Slf4j

@Slf4j
class DemoApplicationTests {
  @Test
  public void test(){
    log.debug("output DEBUG journal.......");
  }
}

How to customize the log level?

The default log level in Spring Boot is INFO. You can also customize the log level yourself. Add the following configuration in the Spring Boot configuration file:

logging.level.root=DEBUG

Spring Boot also supports package level log level adjustment. Add the following configuration to the Spring Boot configuration file:

logging.level.com.example.demo=INFO

How is the log output to a file?

The logs in Spring Boot are output to the console by default. Publishing to the server log is certainly not enough. We can output the logs to a file, and then view the contents of the log file on the server through the cat tail command, so as to view the operation records of the system. Add the following configuration to the Spring Boot configuration file:

# Specifies the path to the log file
logging.file.path:
# The file name of the log. The default is spring log
logging.file.name:

Note: the official document says that these two attributes cannot be configured at the same time, otherwise they will not take effect, so only one needs to be configured.

How to customize log configuration?

The above operations are all configured based on the configuration provided by Spring Boot. How can we customize the configuration? For example, the format of the output log file name, and so on.

The official document of Spring Boot indicates that according to different logging systems, the following log configuration file names can be loaded correctly, as follows:

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

Spring Boot official recommendation gives priority to using the file name with - spring as your log configuration. Therefore, you only need to create logback spring. Net in the src/resources folder XML, and the content of the configuration file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <!-- Define log storage directory -->
    <property name="logPath" value="logs"/>
    <!-- Format of log output-->
    <property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} %L %M -
%msg%xEx%n"/>
    <contextName>logback</contextName>
    <!--Output to console ConsoleAppender-->
    <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
        <!--Display format layout-->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${PATTERN}</pattern>
        </layout>
        <!--Filter. Only the log information filtered to the specified level will be output. If level by ERROR,Then the console will only output
        ERROR journal-->
        <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">-->
        <!-- <level>ERROR</level>-->
        <!-- </filter>-->
    </appender>
    <!--Normal log file, output to file-->
    <appender name="fileDEBUGLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!--If you just want Info Level logs, just filtering info Still output Error Log, because Error High level,
        Therefore, we can avoid output by using the following strategy Error Log of-->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--filter Error-->
            <level>Error</level>
            <!--Prohibit matching-->
            <onMatch>DENY</onMatch>
            <!--No match is allowed-->
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <!--Log name, if not File Property, then only FileNamePattern File path rules for
        If at the same time<File>and<FileNamePattern>,So what is the log of the day<File>,Tomorrow will automatically replace today
        Change the name of your log to today's date. That is,<File> All the logs are of the same day.
        -->
        <File>${logPath}/log_demo.log</File>
        <!--Scrolling strategy, scrolling by time TimeBasedRollingPolicy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--File path,Define the log segmentation method - archive the log of each day into a file,To prevent the log from filling the whole
            disk space-->
            <FileNamePattern>${logPath}/log_demo_%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--Keep only the logs of the last 90 days-->
            <maxHistory>90</maxHistory>
            <!--Used to specify the maximum size of the log file. When this value is reached, the old log will be deleted-->
            <!--<totalSizeCap>1GB</totalSizeCap>-->
        </rollingPolicy>
        <!--Log output encoding format-->
        <encoder>
            <charset>UTF-8</charset>
            <pattern>${PATTERN}</pattern>
        </encoder>
    </appender>
    <!--output ERROR Log to the specified file-->
    <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!--If you just want Error Level logs need to be filtered. The default is info Level, ThresholdFilter-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>Error</level>
        </filter>
        <!--Log name, if not File Property, then only FileNamePattern File path rules for
        If at the same time<File>and<FileNamePattern>,So what is the log of the day<File>,Tomorrow will automatically replace today
        Change the name of your log to today's date. That is,<File> All the logs are of the same day.
        -->
        <File>${logPath}/error.log</File>
        <!--Scrolling strategy, scrolling by time TimeBasedRollingPolicy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--File path,Define the log segmentation method - archive the log of each day into a file,To prevent the log from filling the whole
            disk space-->
            <FileNamePattern>${logPath}/error_%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--Keep only the logs of the last 90 days-->
            <maxHistory>90</maxHistory>
            <!--Used to specify the maximum size of the log file. When this value is reached, the old log will be deleted-->
            <!--<totalSizeCap>1GB</totalSizeCap>-->
        </rollingPolicy>
        <!--Log output encoding format-->
        <encoder>
            <charset>UTF-8</charset>
            <pattern>${PATTERN}</pattern>
        </encoder>
    </appender>
    <!--Specifies the most basic log output level-->
    <root level="DEBUG">
        <!--appender Will be added to this loger-->
        <appender-ref ref="consoleLog"/>
        <appender-ref ref="fileDEBUGLog"/>
        <appender-ref ref="fileErrorLog"/>
    </root>
    <!-- Definition assignment package Log level of-->
    <logger name="org.springframework" level="DEBUG"></logger>
    <logger name="org.mybatis" level="DEBUG"></logger>
    <logger name="java.sql.Connection" level="DEBUG"></logger>
    <logger name="java.sql.Statement" level="DEBUG"></logger>
    <logger name="java.sql.PreparedStatement" level="DEBUG"></logger>
    <logger name="io.lettuce.*" level="INFO"></logger>
    <logger name="io.netty.*" level="ERROR"></logger>
    <logger name="com.rabbitmq.*" level="DEBUG"></logger>
    <logger name="org.springframework.amqp.*" level="DEBUG"></logger>
    <logger name="org.springframework.scheduling.*" level="DEBUG"></logger>
    <!--definition com.xxx..xx..xx The log information under the package is not uploaded, but directly output to fileDEBUGLog and fileErrorLog These two appender
    In, the log level is DEBUG-->
    <logger name="com.xxx.xxx.xx" additivity="false" level="DEBUG">
        <appender-ref ref="fileDEBUGLog"/>
        <appender-ref ref="fileErrorLog"/>
    </logger>
</configuration>

You can also customize the name of the configuration file and add the following configuration to the Spring Boot configuration file:

logging.config=classpath:logging-config.xml

Explanation of configuration file:

  1. configuration node

    • scan: when this property is set to true, the configuration file will be reloaded if it changes. The default value is true.
    • scanPeriod: set the time interval for monitoring whether the configuration file is modified. If no time unit is given, the default unit is milliseconds. When this property is true, scan takes effect. The default interval is 1 minute.
    • debug: when this property is set to true, the internal log information of logback will be printed out to view the running status of logback in real time. The default value is false.
  2. root node

    This is a required node used to specify the basic log level. There is only one level attribute, and the default value is DEBUG.
    The node can contain zero or more elements. The child node is appender ref, and the tag appender will be added to the logger
    Yes.

  3. contextName node

    Identify a context name. The default is default, which is generally unavailable.

  4. property node

    Mark a context variable with name and value attributes. After defining the variable, you can use ${} to get it.

  5. appender node

    It is used to format the log output node. There are two attributes: name and class. Class is used to specify which output strategy. Commonly used are console output strategy and file output strategy.
    In general, three Appenders need to be defined for log files, namely console output, general log file output and exception log file output.
    This node has several important child nodes, as follows:

    1. filter: log output interceptor. It is not specially customized. Generally, it is OK to use the system's own. However, if you want to separate the logs, such as outputting the log of ERROR level to one file and outputting the log of ERROR level to another file, you need to intercept the log of ERROR level.
    2. encoder: the log format and encoding method used for specific output combined with the pattern node.
    3. File: this node is used to indicate the output location of the log file. It can be an absolute path or a relative path
    4. rollingPolicy: log rollback policy. Here we use TimeBasedRollingPolicy. The time-based rollback policy has the following child nodes, fileNamePattern, and necessary nodes, which can be used to set the log archive at the specified time.
    5. maxHistory: optional node, which controls the maximum number of archive files retained. If the number exceeds, the old files will be deleted. For example, if it is set to 30, the old logs will be deleted after 30 days
    6. totalSizeCap: optional node. It is used to specify the maximum size of the log file. For example, if it is set to 3GB, the old log will be deleted
  6. logger node
    Optional node, used to specify the log output level of the package, which will override the output level of root.
    This node has several important attributes as follows:

    1. Name: the specified package name
    2. Level: optional, the level of the log
    3. addtivity: optional. The default value is true. Pass the information of this logger to the superior. The root node will define log printing. If it is set to false, it will not be uploaded. At this time, you need to define an appender ref node to output.

The above is the whole content of this issue. Don't forget to praise and pay attention to your favorite partners. I'll see you next time. Bye.

Keywords: Java Spring Spring Boot

Added by Jammerious on Sat, 12 Feb 2022 18:16:48 +0200