springboot2.x basic tutorial: log configuration

In the development process of the project, the developers will be familiar with the log. Logs can record the track of program operation, output key information in software operation, assist us in troubleshooting and locating problems, optimize program performance, and monitor program operation status. It is not unimportant.
The spring-boot-starter of the SpringBoot project refers to spring-boot-starter-logging by default, where the bottom layer uses the logback logging framework, and the logging function can be used with zero configuration by default.
Before explaining the springboot log configuration, let's briefly talk about the basic knowledge of JAVA logs.

Timing of logging

  • Record the startup parameters of program initialization and judge the running status of the program
  • The code throws an exception and records the abnormal state of the program
  • The business process does not match the expected result, and the business abnormal state is recorded
  • System core business, core authority operation. For example, operation records such as login and payment are usually included in the database for analysis.

Java logging framework

For log frameworks, we usually see nouns such as log4j and logback, and we also encounter conflicts between our own project and the log library of a third-party jar.
The first time you come into contact with these, you may feel like clouds and mists are incomprehensible. Here is a brief introduction to the relationship between the Java logging framework. More specific historical reasons, details. There are several articles on the Internet that are very good, and I will attach them to your own reading and understanding:

  1. Know that there is an article above: java log frame analysis
  2. There is an article on the blog: Introduction to Java Common Log Framework

After reading the above article, a brief summary of the Java logging framework is divided into 3 categories:

  • The specific implementation of the Java logging framework: log4j1.x, JUL (Java Util Log), Logback, log4j2-core
  • The facade object of the Java logging framework, only provides the interface but does not provide specific implementation: JCL (Commons Logging), SLF4J (The Simple Logging Facade for Java), log4j2-api
  • Adapter between Java log frameworks, in order to convert different log frameworks: jcl-over-slf4j, slf4j-jcl, log4j-over-slf4j, slf4j-log4j12, etc.
    Picture source online

Best practices for logging framework (source reference link, here is just an excerpt):

  1. Always use Log Facade instead of specific Log Implementation
  2. Only add a Log Implementation dependency
  3. The specific log implementation dependency should be set to optional and use runtime scope
  4. If necessary, exclude Log Impementation dependencies in dependent third-party libraries
  5. Avoid outputting unnecessary logs, and unnecessary log fields such as line numbers affect program performance

SpringBoot log configuration

Log dependency

Springboot uses the combination of SLF4J+Logback to record logs by default, and you can see the dependencies, so we don't need to introduce them.

springboot log configuration

logging:
  level:
    #包的日志级别
    org.springframework.web: DEBUG
  #自定义log信息
  config: classpath:config/logback-spring.xml
  pattern:
    #控制台的日志输出格式
    console: '%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n'
    #文件的日志输出格式
    file: '%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n'
  file:
    #日志名称
    name: app.log
    #存储的路径
    path: /var/log/
    #存储的最大值
    max-size: 50MB
    #保存时间
    max-history: 7

Custom log configuration

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--获取变量名中关于日志存储的路径与存储名称-->
    <springProperty scope="context" name="logPath" source="logging.file.path"/>
    <springProperty scope="context" name="logName" source="logging.file.name"/>
    <!--输出到控制台的appender-->
    <appender name="Console"
              class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable
            </Pattern>
        </layout>
    </appender>
    <!--输出到文件的appender-->
    <appender name="RollingFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${logPath}/${logName}</file>
        <encoder
                class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
        </encoder>

        <rollingPolicy
                class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily and when the file reaches 10 MegaBytes -->
            <fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <!--开发环境基本级别为DEBUG-->
    <springProfile name="dev">
        <root level="DEBUG">
            <appender-ref ref="Console"/>
        </root>
    </springProfile>
    <!--生产环境输入到文件中-->
    <springProfile name="prod">
        <root level="INFO">
            <appender-ref ref="RollingFile"/>
        </root>
    </springProfile>
</configuration>

A thousand miles begins with a single step. Here is the eighth article in the SpringBoot tutorial series. All project source codes can be downloaded on my GitHub .

Guess you like

Origin blog.csdn.net/github_35592621/article/details/108248869
Recommended