Integrated Log Management for SpringBoot Development Cases

Every morning we get up and a new day starts.We can choose to drive today, or we can choose to drive us today.When we actively design today, then we can define the criteria for success and win in today's game, but if we go through today passively, we may regret today by ourselves tomorrow.

Summary

Reference documents: Logging

By the way, it's okay to refer to the following text, of course, if you don't understand it, we have A-channel translation. If the translation is not accurate, the configuration will be provided later to share with you.

Spring Boot uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available.
By default, If you use the 'Starters', Logback will be used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J or SLF4J will all work correctly.

Use

The pom.xml configuration doesn't get pulled around here, it depends on adding it yourself.

Console output

Configuration log parameters only need to be written in application.properties or application.yml, of course, this is just the basic configuration.

#As mentioned in the official documentation, SpringBoot's Logging configuration has seven levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
#root log output at INFO level
logging.level.root=INFO
#springframework.web log output at WARN level
logging.level.org.springframework.web=WARN
#hibernate log output at ERROR level
logging.level.org.hibernate=ERROR

With the above configuration in place, we can start the project and print the Log information in the console.

However, in production environments, logs are often stored as files on the server. Here's how the spring-boot logs are output.

File output

logging.file=spring_boot.log
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n

When the configuration is complete, we start the project again, and a spring_boot.log log log file is generated in the root directory.

However, the small partners who have experienced the project online, in fact, such configuration can not meet the production requirements.For example, distinguish between normal logs and error logs, store logs by log, maximum capacity of a single log file, delete files how many days ago, and so on!Here's a more advanced configuration to share with you.

Custom log configuration

Depending on your logging system, the following files will be loaded:

Logback: logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy

Log4j2: log4j2-spring.xml or log4j2.xml

JDK (Java Util Logging): logging.properties

Logback, Log4j2, and Log4j are supported for spring-boot log management, and according to the above instructions, we can define file naming.

Below we use the specified configuration file of Logback for more advanced log configuration.

logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- scan If the configuration file changes, it will be reloaded  scanPeriod Detection Interval Time-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>spring-boot-log</contextName>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <!-- Normal Log -->
    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>log/spring-boot-log-info.log</file>
        <!-- Cycle policy: creating log files based on time -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
             <!-- Log Naming:Single file larger than 128 MB By Time+Self-increasing i generate log file -->
            <fileNamePattern>log/spring-boot-log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>128MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- Maximum save time: 30 days-->
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <append>true</append>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
     <!-- Error Log -->
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>log/spring-boot-log-error.log</file>
        <!-- Cycle policy: creating log files based on time -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- Log Naming:Single file greater than 2 MB By Time+Self-increasing i generate log file -->
            <fileNamePattern>log/spring-boot-log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>2MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- Maximum save time: 180 days-->
            <maxHistory>180</maxHistory>
        </rollingPolicy>
        <append>true</append>
        <!-- Log format -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!-- Log Level Filter -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
             <!-- Level of filtering -->
             <level>ERROR</level>
             <!-- Operation when matching: Receive (record) -->
             <onMatch>ACCEPT</onMatch>
             <!-- Action in case of mismatch: Reject (no record) -->
             <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <!-- Console -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- Log format -->
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!--This log appender For development purposes, only the bottom level is configured, and the log level output by the console is greater than or equal to this level of log information-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
    </appender>
    <!-- additivity Avoid execution twice -->
    <logger name="com.itstyle"  level="INFO"  additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="INFO_FILE"/>
        <appender-ref ref="ERROR_FILE"/>
    </logger>
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="INFO_FILE" />
        <appender-ref ref="ERROR_FILE" />
    </root>
</configuration>

If we use the specified configuration file for Logback, the configuration in application.properties can be cancelled.

test

After configuring, we did a test that made it easy for me to change the info and error log capacity maxFileSize to 2 MB.

Then start the program:

/**
 * Creator https://blog.52itstyle.com
 * Created July 24, 2017
 */
@EnableAutoConfiguration
public class Application  {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args);
          while(true){
            logger.info("Normal Log");
            logger.error("Error Log");
          }
    }
}

Execute for a period of time if the following log file is generated under the project path to indicate that the configuration was successful.

Code: http://git.oschina.net/52itstyle/spring-boot-log

Author: Xiao Qi

Source: https://blog.52itstyle.com

Copyright of this article is owned by the author and the Cloud Community. You are welcome to reproduce it, but this statement must be retained without the author's consent and given in a prominent place on the article page. If you have questions, you can email ( 345849402@qq.com ) Consulting.

Keywords: Spring xml Java log4j

Added by chitta_pk on Sat, 08 Jun 2019 21:55:51 +0300