SpringBoot2使用 Log4j2
时间:2023-10-16 17:37:02
参考博客: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.bootgroupId> <artifactId>spring-boot-starter-webartifactId> <exclusions> <exclusion> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-loggingartifactId> exclusion> exclusions> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-log4j2artifactId> 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的日志配置
例如:
<Configuration status=/span>"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来使用