[Miss sister's detailed introduction to SpringBoot tutorial] SpringBoot integration log slf4j and logback (4)

Log frameworks on the market:

logback ,log4j log4j2 , slf4j

1. What is a log?

Log: Information describing the real-time operating status of the system.

For example: System.out.println() statement is a kind of lowest level log.

2. What is the log facade and log implementation?

Log facade: It is the abstraction layer of log implementation.

Log realization: the realization of specific log function.

Why not directly use the log implementation, but made another thing called the log facade?

Because of the log implementation, there may be some code optimizations and changes to avoid affecting the user's use in the project. Use the unified interface of the log facade. Assuming that the implementation layer code is changed, the user uses the log in the project to call the interface And so on, it will not be affected.

3. What are the common log frameworks?

Log facade (abstract layer) Log implementation
JCL SLF4j JUL (java.util.logging) log4 logback log4j2 logback

In actual use, a log facade of an abstraction layer is selected to be used with a low-level log implementation.

The collocation selected by default in SpringBoot is: slf4j+logback

Log facade: slf4j

Log implementation: logback

springboot: The bottom layer is the spring framework, and the spring framework uses JCL by default

SpringBoot chooses slf4j and logback

4. Use of slf4j

In the future development, the call of the logging method should not directly call the log implementation class, but call the method in the log abstraction layer

Each log implementation framework has its own configuration file. After using slf4j, the configuration file is still made into the configuration file of the log implementation framework (that is, the configuration file for which implementation framework is used).

5. Legacy issues

(slf4j + logback) : Spring(commons-loggin)、Hibernate(jboss-loggin)、Mybatis

If we use slf4j and logback, but after integrating other projects, other projects use a variety of logging frameworks, then we need unified logging, and we use slf4j to output all logs.

How to unify all logs in the system to slf4j:

1. Exclude other log frameworks in the system first

2. Replace the original log framework with an intermediate package

3. We import other implementations of slf4j

6. SpringBoot log relationship

Pom dependency analysis tips:

Choosing this will show the dependency analysis of the graph shape.

(1) The bottom layer of SpringBoot uses slf4j+logback for logging

(2) SpringBoot also replaced other logs with slf4j

(3) An intermediate conversion package was used when replacing

(4) What if we want to introduce other frameworks? Be sure to remove the default log dependency of this framework.

For example: we have introduced the Spring framework, then we must exclude the default log dependency of the Spring framework commons-logging

SpringBoot can automatically adapt to all logs, and the bottom layer uses slf4j+logback to record logs. When other frameworks are introduced, the underlying logging framework that the framework depends on is excluded, then SpringBoot can adapt to the framework.

7. The use of logs in SpringBoot

Use of logs:

@SpringBootTest
class DemoApplicationTests {
    
    

    // 获取日志记录器
    Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    void contextLoads() {
    
    
        // 日志级别 trace < debug < info < warn < error
        // 可以调整日志的输出级别,日志就只会在这个级别及以后的高级别生效
        logger.trace("这是trace日志...");
        logger.debug("这是debug日志...");
        // SpringBoot默认是 info 级别的
        logger.info("这是info日志...");
        logger.warn("这是warn日志...");
        logger.error("这是error日志...");
    }

}

Log level trace <debug <info <warn <error

The application.ymllog output level can be specified in the file, and the default level of springboot is info级别.

logging:
  level:
    # 需要指定哪个包下的日志级别
    com.example: trace
  file:
    # 在当前磁盘的根目录下创建spring和log文件夹,里边创建springboot.log日志文件
    path: /spring/log
  # 可以使用绝对路径
  # path: E:\mylog
  # 指定日志文件名,若不指定日志路径,默认在根目录下
  # name: springboot.log

8. Specify the log output format in SpringBoot

If you use logback, you can directly put the logback.xml or logback-spring.xml file in the resources directory to take effect.

logback.xml 和 logback-spring.xml 的区别:

logback-spring.xml file can use <springProfile name="">the tag to specify which format to use in which the development environment.

The complete logback-spring.xml file can be used in the resources directory:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 尽量别用绝对路径,如果带参数不同容器路径解释可能不同,以下配置参数在pom.xml里 -->
    <property name="log.root.level" value="INFO"/> <!-- 日志级别 -->
    <property name="log.other.level" value="INFO"/> <!-- 其他日志级别 -->
    <property name="log.base"
              value="logs"/> <!-- 日志路径,这里是相对路径,web项目eclipse下会输出到eclipse的安装目录下,如果部署到linux上的tomcat下,会输出到tomcat/bin目录 下 -->
    <property name="log.moduleName" value="blog"/>  <!-- 模块名称, 影响日志配置名,日志文件名 -->
    <property name="log.max.size" value="20MB"/> <!-- 日志文件大小 -->

    <!--控制台输出 -->
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger.%method:%L) - %cyan(%msg%n)
            </pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debug</level>
        </filter>
    </appender>

    <!-- info文件输出 -->
    <appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}-info.log
        </File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果 是web项目会保存到Tomcat的bin目录 下 -->
        <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}-info-%d{yyyy-MM-dd}.%i.log
            </FileNamePattern>
            <!-- 当天的日志大小 超过${log.max.size}时,压缩日志并保存 -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <!-- 日志输出的文件的格式  -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger{56}.%method:%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- debug文件输出 -->
    <appender name="debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}-debug.log
        </File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果 是web项目会保存到Tomcat的bin目录 下 -->
        <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}-debug-%d{yyyy-MM-dd}.%i.log
            </FileNamePattern>
            <!-- 当天的日志大小 超过${log.max.size}时,压缩日志并保存 -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <!-- 日志输出的文件的格式  -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger{56}.%method:%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- warning文件输出 -->
    <appender name="warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}-warn.log
        </File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果 是web项目会保存到Tomcat的bin目录 下 -->
        <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}-warn-%d{yyyy-MM-dd}.%i.log
            </FileNamePattern>
            <!-- 当天的日志大小 超过${log.max.size}时,压缩日志并保存 -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <!-- 日志输出的文件的格式  -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger{56}.%method:%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- error文件输出 -->
    <appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}-error.log
        </File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果 是web项目会保存到Tomcat的bin目录 下 -->
        <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}-error-%d{yyyy-MM-dd}.%i.log
            </FileNamePattern>
            <!-- 当天的日志大小 超过${log.max.size}时,压缩日志并保存 -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <!-- 日志输出的文件的格式  -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger{56}.%method:%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- error文件输出 -->
    <appender name="all" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}-all.log
        </File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果 是web项目会保存到Tomcat的bin目录 下 -->
        <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}-all-%d{yyyy-MM-dd}.%i.log
            </FileNamePattern>
            <!-- 当天的日志大小 超过${log.max.size}时,压缩日志并保存 -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <!-- 日志输出的文件的格式  -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger{56}.%method:%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- 为某个包下的所有类的指定Appender 这里也可以指定类名称例如:com.aa.bb.ClassName -->
    <logger name="com.jg.blog" additivity="false">
        <level value="debug"/>
        <appender-ref ref="stdout"/>
        <appender-ref ref="info"/>
        <appender-ref ref="debug"/>
        <appender-ref ref="warn"/>
        <appender-ref ref="error"/>
        <appender-ref ref="all"/>
    </logger>
    <!-- root将级别为“DEBUG”及大于“DEBUG”的日志信息交给已经配置好的名为“Console”的appender处理,“Console”appender将信息打印到Console -->
    <root level="info">
        <appender-ref ref="stdout"/> <!-- 标识这个appender将会添加到这个logger -->
        <appender-ref ref="info"/>
        <appender-ref ref="debug"/>
        <appender-ref ref="warn"/>
        <appender-ref ref="error"/>
        <appender-ref ref="all"/>
    </root>
</configuration>

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113931198