参考博客:https://blog.csdn.net/dyc87112/article/details/122252958
一、如何选择 Logback 还是 Log4j2
二、如何SpringBoot中引入Log4j2
1、pom文件中引入log4j2启动器
在pom.xml中引入Log4j2的Starter依赖spring-boot-starter-log4j2,同时排除默认引入的spring-boot-starter-logging
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
2、application.properties指定配置文件位置
在配置文件application.properties中,通过logging.config配置指定log4j2的配置文件位置
logging.config=classpath:log4j2.xml
注意 其实这一步也可以不需要,SpringBoot 默认会使用resource文件夹下的 log4j2-spring.xml 或者 log4j2.xml
作为Log4j2的配置文件
3、在resource目录下新建log4j2.xml
在resource目录下新建log4j2.xml(这里不绝对,根据第二步中配置的内容来创建),然后加入log4j2的日志配置
例如:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
==注意:==建议您至少要用2.17.0以上的版本(如果用的Spring Boot 2.6.2+,那已经是2.17.0了,不需要担心)。当然,目前最新已经到2.17.1,您也可以自己升级到2.17.1来使用