参考资料
pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
安装
首先需要屏蔽 Spring Boot 自带的 Log 工具,修改 pom.xml
<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>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
配置
新建 resources/log4j2.xml
文件
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<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="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
在 application.properties
中配置:
logging.config=classpath:log4j2.xml
这里有一个官方的配置参考:https://logging.apache.org/log4j/2.x/manual/configuration.html#XML
使用
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 演示如何使用 Logger
*
* @author Where
*/
public class Demo {
private static final Logger logger = LoggerFactory.getLogger(Demo.class);
public void index() {
logger.info("index");
}
}