Spring Boot study notes (seven) - log management


premise

This blog post is the seventh part of this set of Spring Boot study notes - log management. The main content includes how to write logback configuration files and how to call the log framework. If you need to know the summary information about Spring Boot or the index information of blog posts, please go to:
"Summary"


Contents of the log configuration file

In fact, after writing log4Jthe configuration files of the log framework, you will find that the content of these configurations is similar, and the role is nothing more than clarifying the following:

  • The output of the log is divided into two parts
    • on the console
    • in the log file
  • Configuration file path and name rules
  • AppenderScrolling rules for appender( )
    • scroll by size
    • scroll by time
  • Level of log output ( Info, Warn, Error, Fatal)

Logback configuration instructions

Due to the large number of configuration attributes, it would be more complicated to explain one by one, and the hierarchical relationship is not easy to explain, so the code is directly posted, and the explanations are all in the comments.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- %m输出的信息, %p日志级别, %t线程名, %d日期, %c类的全名, %i索引 -->
    <!-- appender是configuration的子节点,是负责写日志的组件 -->
    <!-- ConsoleAppender把日志输出到控制台 -->
    <!--    <property name="CONSOLE_LOG_PATTERN" -->
    <!--               value="%date{yyyy-MM-dd HH:mm:ss} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger) | %msg%n"/> -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!--<pattern>${CONSOLE_LOG_PATTERN}</pattern> -->
            <pattern>%date{yyyy-MM-dd HH:mm:ss} %highlight(%-5level) (%file:%line\)- %m%n</pattern>
            <!-- 控制台也要使用utf-8,不要使用gbk -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
    <!-- 1.先按日期存日志,日期变了,将前一天的日志文件名重命名为xxx%日期%索引,新的日志仍然是sys.log -->
    <!-- 2.如果日期没有变化,但是当前日志文件的大小超过1kb时,对当前日志进行分割 重名名 -->
    <appender name="syslog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>logs/sys.log</File>
        <!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->  
        <!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->  
            <!-- 文件名:log/sys.2017-12-05.0.log -->
            <fileNamePattern>logs/sys.%d.%i.log</fileNamePattern>
            <!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->
            <maxHistory>30</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy  class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">      
                <!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->    
                <maxFileSize>10MB</maxFileSize>      
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>      
            <!-- pattern节点,用来设置日志的输入格式 -->  
            <pattern>      
                %d %p (%file:%line\)- %m%n    
            </pattern>      
            <!-- 记录日志的编码 -->  
            <charset>UTF-8</charset> <!-- 此处设置字符集 -->     
        </encoder>
    </appender>
    <!-- 控制台日志输出级别 -->
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
    <!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->  
    <!-- com.implementist.artanis为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
    <!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE  -->  
    <logger name="com.implementist.demo" level="DEBUG">
        <appender-ref ref="syslog" />      
    </logger>
</configuration>


Two properties to note

In the above configuration information, it should be noted that the file path has several different situations <File>from these two attributes:<fileNamePattern>

  • logs/: Create a folder in the relative path of the project logs, and generate log files under it. After testing, when using the package to start the project, a folder JARwill be generated in its same level directory .logs
  • /logs/: Create a folder in the relative path of the system logs, and generate the log file under it. This method has no problem in the actual development and deployment environment, but it will cause the file Travis CIto fail to be created during continuous integration , which will lead to the entire failure.logsbuild

Configure for project references

This is very simple in the Spring Boot project

  • Name the above configuration file as logback-boot.xml, and place it src/main/resourcesin a folder.
  • application.ymlAdd the following to the configuration file :
logging:
  config: classpath:logback-boot.xml

output log

In fact, it has been written in the previous blog post. We can directly call variables for log Lombokoutput by adding an annotation to the class . For example:@Slf4jlog

@Slf4j
public class TestClass {
    
    
	public void anyMethod(){
    
    
		...
		log.info("Some log message of info level");
		log.debug("Some log message of debug level");
		log.warn("Some log message of warn level");
		log.error("Some log message of error level");
		...
	}
}

postscript

The knowledge of log configuration is relatively small, basically just copy a copy of the configuration information and then modify it by yourself to use it. But the format and protocol of log output are also very important. As a mature software engineer, you still need to learn how to log gracefully, and then summarize after learning.

Guess you like

Origin blog.csdn.net/Mr_Megamind/article/details/102898377