[Spring] Spring6 enables Log4j2 logging framework

Based on the latest Spring framework tutorial of [Power Node], the first Spring 6 tutorial on the entire network, learn spring from scratch to advanced with Lao Du and Lao Du’s original notes https://www.yuque.com/docs/share/866abad4-7106 -45e7-afcd-245a733b073f?# "Spring6" is organized, document password: mg9b


Spring related articles are compiled and summarized at: https://www.yuque.com/u27599042/zuisie


  • Starting from Spring 5, the integrated logging framework supported by the Spring framework is Log4j2
  • Enabling the logging framework helps us better track the program, and when the program goes wrong, we can find and eliminate errors faster.

Introduce the dependency of Log4j2

<!--log4j2的依赖-->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.19.0</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-slf4j2-impl</artifactId>
  <version>2.19.0</version>
</dependency>

Provide log4j2.xml configuration file

  • Provide the log4j2.xml configuration file under the class root path
  • The file name of the configuration file is fixed to: log4j2.xml, and the file must be placed in the class root path
  • The file name of the configuration file is fixed, and the location is also fixed. It must be in the root directory of the class and its subdirectories.
  • image.png
<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    
    <loggers>
        <!--
            level指定日志级别,从低到高的优先级:
                ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
            达到相应的级别才会输出日志信息
            级别越低输出的日志信息越多
        -->
				<!-- 日志输出级别为 DEBUG,该级别之下的日志不会输出 -->
        <root level="DEBUG">
            <appender-ref ref="spring6log"/>
        </root>
    </loggers>
    
    <appenders>
        <!--输出日志信息到控制台-->
        <console name="spring6log" target="SYSTEM_OUT">
            <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [%t] %-3level %logger{1024} - %msg%n"/>
        </console>
    </appenders>

</configuration>

Use the logging framework

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@org.junit.Test
public void testLog() {
    
    
    // 获取日志记录器对象(记录日志需要一个日志记录器)
    // 获取Test类的日志记录器对象,只要是Test类中的代码执行记录日志的话,就输出相关的日志信息。
    Logger logger = LoggerFactory.getLogger("cw.spring.study.test.Test");
    
    // 记录日志,记录不同的级别的日志
    // 输出日志时,根据配置文件中设置的输出日志级别进行输出
    logger.info("我是一条消息");
    logger.debug("我是一条调试信息");
    logger.error("我是一条错误信息");
    logger.trace("我是一条查找追踪信息");
}

Guess you like

Origin blog.csdn.net/m0_53022813/article/details/131987957