Slf4j log usage

Tip: Here are two ways to use SLF4J logs.

The first method: print logs in traditional code mode   

The second type: use lombok's @slf4j annotation to print logs

1. Print logs in traditional code mode

1. Introduce related log dependencies

Among them, Slf4j only does the log panel, and Log4j2 does the log core.

            <!-- log4j2适配slf4j包 -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-to-slf4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <!-- log4j2核心包(包含slf4j) -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <!-- log4j2核心包 -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
                <version>${log4j.version}</version>
            </dependency>

2. Set the configuration file

The YML file is configured as follows:

# 日志配置
logging:
  config: classpath:logback/logback.xml
  file:
    name: D:/XX
  level:
    com.xx.xx: info
    com.xx.xx.xx: debug

logging.config : When the specified project starts, read the logback.xml log configuration file
logging.level : Configure the logging and log level of the application under the path of the specified package.

file.name: Specifies the log generation path and name, and the abstract path is generated under the project by default.

log level:

  1. Trace (tracking): Generally used to track the detailed program running flow, such as which method is run and which branch is entered during the running process of the program. Through the running process of the trace program, you can judge whether the program is running according to the expected logic
  2. debug (debugging): This type of log is often used to judge whether there is a bug scene, and often records the detailed information of the code running, such as the parameter information passed in by the method call
  3. info (message): It is used to record some key information about the running of the program. It does not record the entire process of running the program like trace does, nor does it record detailed information to solve problems like debug. info records the operation information of the entire system, such as which stage the system has reached and which state it has reached
  4. warn (warning): used to record some warning information. The warning message indicates that the program has entered a special state in which the program can continue to run, but it is not recommended to let the program enter this state, because this state may cause problems with the results
  5. error (error): It is used to record the error information at runtime, indicating that there are problems that need to be solved during the running of the program, often some exceptions. When using the error log, the detailed reason for the exception will generally be recorded
     

The log priority from high to low is trace, debug, info, warn, error. Relatively speaking, fewer and fewer logs will be printed.

The logback.xml configuration is as follows:

Add a new logback folder under the resource directory, and create a logback.xml log file under the folder

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 应用名称(项目名称) -->
    <property name="APP_NAME" value="log-test"/>
    <!--定义日志文件的存储地址,yml配置过这里就不用配置-->
    <property name="LOG_HOME" value="/logs/${APP_NAME}"/>
    <!-- 定义日志格式  -->
    <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] [%-30.30logger{30}] %msg%n"/>
    <!-- 高亮日志格式  -->
    <property name="HIGHLIGHT_PATTERN" value="%yellow(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %green(%logger{50}) - %highlight(%msg) %n"/>

    <!-- 控制台输出-高亮 -->
    <appender name="CONSOLE-WITH-HIGHLIGHT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${HIGHLIGHT_PATTERN}</pattern>
        </encoder>
    </appender>

    <!--文件输出的格式设置 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

        <!-- 如果是 true,日志会被安全的写入文件,即使其他的FileAppender也在向此文件做写入操作,效率低,默认是 false -->
        <prudent>false</prudent>

        <!-- 日志日常打印日志文件,yml配置过这里就不用配置,生成日志示例:/logs/log-test/info.log -->
        <file>${LOG_HOME}/info.log</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <!-- 压缩日志的路径和日志格式,示例:info-2023-05-26_21.log.zip,%d{yyyy-MM-dd}:表示文件名称包含日期,%i:表示当前是第几个压缩文件 -->
            <fileNamePattern>${LOG_HOME}/info-%d{yyyy-MM-dd}_%i.log.zip</fileNamePattern>

            <!-- 如果按天来回滚,则最大保存时间为7天,7天之前的都将被清理掉 -->
            <maxHistory>7</maxHistory>

            <!-- 日志总保存量为10GB,超过该日志总量的最早的日志压缩包会被清除 -->
            <totalSizeCap>10GB</totalSizeCap>

            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!--文件达到 最大100MB时会被压缩和切割 -->
                <maxFileSize>100MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>

        </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>

    </appender>

    <!-- 日志输出级别,yml配置过这里就不用配置 -->
    <logger name="com.xx.xx" level="INFO"/>
    <logger name="com.xx.*" level="DEBUG"/>
   <!-- 定义对应级别的appender -->
    <root level="INFO">
        <appender-ref ref="CONSOLE-WITH-HIGHLIGHT"/>
        <appender-ref ref="FILE"/>
    </root>

</configuration>

3. Use log printing

@SpringBootTest
class XX{
    //这里填写你对应的类对象
    public static final Logger LOGGER = LoggerFactory.getLogger(XX.class);
    // 快速入门
    @Test
    public void testSlf4j() throws Exception {
        
        // 日志输出
        LOGGER.error("error");
        LOGGER.warn("warn");
        LOGGER.info("info"); // 默认级别
        LOGGER.debug("debug");
        LOGGER.trace("trace");

        // 使用占位符输出日志信息
        String name = "rikka";
        Integer age = 10;
        LOGGER.info("用户:{},{}", rikka, age);


        // 将系统异常信息输出
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            LOGGER.error("出现异常:", e);
        }
    }
}

2. Use lombok's @slf4j annotation to print logs

1. Introduce dependencies

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2. Add plugin

3. Set the configuration file

Just copy the yml and xml configurations above (traditional code method to print logs) here.

4. Print log

@Slf4j
@RestController
public class TestLog{
    @GetMapping("/TestLog")
    public String queryList() {
        String s = "rikka";
        log.error(s);
        log.warn(s);
        log.info(s);
        log.debug(s);
        log.trace(s);
        return s;
    }

}


Summarize

Using lombok will increase the degree of code coupling, and plug-ins need to be installed, it will not work properly when the JDK is upgraded, and other team members who require collaborative development during the development process will also use lombok simultaneously. If you exclude it when using lombok's suggestion for packaging, doing so will not affect the use of setters, getters, and logs.

おすすめ

転載: blog.csdn.net/weixin_58403235/article/details/131242457
おすすめ