SpringBoot integrates slf4j log system

Author platform:

| CSDN:blog.csdn.net/qq\_4115394…

| Nuggets: juejin.cn/user/651387…

| Zhihu: www.zhihu.com/people/1024…

| GitHub: github.com/JiangXia-10…

| WeChat public account: 1024 notes

This article is about 4777 words, and the estimated reading time is 11 minutes

foreword

As one of the important parts of an application system, the log system can help us find and locate problems in a timely manner if there are problems in the online environment of the system, so as to solve problems, ensure high availability of services, and reduce production accidents. occur. So the importance of the log is self-evident.

There are many log frameworks used in Java development, such as JUL (java.util.logging), log4j, logback, JCL (Jakarta commons-logging) and so on. SpringBoot provides a logging system. SpringBoot chooses the combination of SLF4J + Logback by default. If you do not need to change to other logging systems (such as Log4j2, etc.), no redundant configuration is required. LogBack will print logs to the console by default. Since new Spring Boot projects generally refer to spring-boot-starter or spring-boot-starter-web, and these two starting dependencies already include dependencies on spring-boot-starter-logging, so we do not need additional Add dependencies.

Next, this article mainly summarizes the SpringBoot integrated slf4j log configuration currently used in the project.

what is slf4j

slf4j, the full name is Simple Logging Facade for Java****, which is a simple facade log . It is a specification, standard, and interface formulated for all log frameworks, not a specific implementation of a framework, and it only serves various log systems.

slf4j provides a unified interface for recording logs, and abstracts the specific implementation of different log systems, as long as it records according to the method provided, the final log format, recording level, output method, etc. are bound to specific log systems to fulfill. If slf4j is used to record logs in the project, and log4j is bound (the corresponding jar package dependency is configured in pom. Just replace the jar package log4j with logback, and there is no need to modify the code of the log file at all.

As mentioned earlier, SpringBoot chooses the combination of SLF4J + Logback by default. If you do not need to change to other log systems, you can use it without redundant configuration. First, let's look at the simplest usage, as follows, introduce Logger logging in the startup class, and see the printed log results:

public class SpringbootdemoApplication {
    private static final Logger logger = LoggerFactory.getLogger(SpringbootdemoApplication.class);
    public static void main(String[] args) {
        logger.info("===============项目启动了===============");
        SpringApplication.run(SpringbootdemoApplication.class, args);
        logger.info("===============启动成功了===============");
    }
}
复制代码

After the project starts successfully, the console log information is as follows:

The main method here is getLogger(xxxxxxx.class) of LoggerFactory. This method is to pass the current class as an input parameter, and the output log will display the corresponding xxx class name. The advantage of this statement is that it is convenient to locate logs, and accurately writing class information can provide the efficiency of quickly locating logs.

Although SpringBoot provides slf4j, logging needs to be configured according to the actual needs of the project in order to help us use it better.

use slf4j

Because springboot integrates slf4j by default, spring-boot-starter or spring-boot-starter-web is generally referenced in new Spring Boot projects, and these two starting dependencies already include spring-boot-starter-logging Dependencies, so there is no need to import additional dependencies in the pom file. If you import sl4j-related dependencies again, multiple errors of the same dependency may appear.

Next, take a look at the relevant configuration in the application.yml configuration file. For the customization of the log, you can configure it in the configuration file:

picture

For example, part of my configuration here is as follows:

logging:
#logging.config是用来指定项目启动的时候,读取哪个配置文件,这里指定的是日志配置文件,即子module项目根路径下的 logback.xml文件,该文件是日志的主要配置信息。
  config: /workspace/java/SpringBootWorkSpace/src/main/resources/locbak.xml
 # level用来配置指定包的路径下应用程序的日志记录,及其日志级别。
  level:
    root: info
    com.springboot.springbootdemo.controller: trace
    com.springboot.springbootdemo.service: debug
    com.springboot.springbootdemo.dao: debug
复制代码

logging.level is used to specify the output level of the application log in a specific package. trace indicates that all log output levels under the com.springboot.springbootdemo.controller package will be trace, and will print out the sql that operates the database. Set it to trace during development to facilitate locating problems. In the production environment, set this log level to The error level is fine.

The five commonly used levels of logs, from low to high according to severity , are: debug (debugging) < info (message) < warn (warning) < error (error) < fatal (serious error) . Usually, several of them can be selected according to the size of the actual required granularity, and the 4 levels of debug, info, warn, and error are commonly used.

The actual development needs to formulate the content of the configuration file of the log, so that after the system is running, the specified logging information we need can be output according to the customized requirements. You can add a locbak.xml configuration file under the resource folder, and set the config path (need to be an absolute path) in the application.yml configuration file as above. The details of the logback.xml configuration file are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="/SpringBootWorkSpace/SpringBootWorkSpace/logs"/>    <!-- 定义日志格式  -->
    <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] [%-30.30logger{30}] %msg%n"/>
    <!-- 控制台输出 -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/SpringBootWorkSpace-Slf4j_%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- 日志输出级别 -->
    <logger name="org.springframework" level="INFO"/>
    <logger name="root" level="INFO"/>
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>
</configuration>
复制代码

In logback.xml, you can define the log output format, path, console output format, file size, storage time, etc. In fact, these files can also be configured in the application.yml configuration file, such as:

logging:
# 日志文件最大的大小
  file:
    max-size: 10MB
   # 日志文件保留天数
    max-history: 7
复制代码

After the above configuration is completed, the startup project will generate the corresponding log file according to the configuration under the log storage path configured in the logback.xml configuration file, as follows:

image.png

image.png

Summarize

The powerful function of the log system is a useful tool for our daily development and system maintenance to troubleshoot and solve problems. Therefore, configuring a reasonable log system according to our actual project will help us better develop and maintain the project system!

If you have any questions or mistakes, welcome to communicate, discuss and learn together!

The source code of this project is at:

github.com/JiangXia-10…

Welcome to download, Star!

related suggestion:

Guess you like

Origin blog.csdn.net/qq_41153943/article/details/124896505