springboot加入log4j2
时间: 2025-05-01 21:38:31 浏览: 17
### 配置和使用Log4j2进行日志记录
#### 1. 排除默认的日志框架
Spring Boot 默认集成了 Logback 日志框架,在引入 Log4j2 的时候需要先排除掉 `spring-boot-starter-logging` 中的 Logback 相关依赖[^2]。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- Exclude the default logging framework -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
```
#### 2. 添加Log4j2依赖
为了使 Spring Boot 使用 Log4j2,需添加相应的 Maven 或 Gradle 依赖项。以下是 Maven 配置示例:
```xml
<!-- Add Log4j2 dependencies -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.x.x</version> <!-- Replace with your desired version -->
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.x.x</version> <!-- Ensure versions match -->
</dependency>
```
上述配置确保 SLF4J API 被映射到 Log4j2 实现中[^1]。
#### 3. 创建Log4j2配置文件
在项目的 `src/main/resources` 文件夹下创建名为 `log4j2.xml` 的配置文件。这是一个基本的 XML 配置模板:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
```
此配置定义了一个控制台输出器 (Console Appender),并设置了全局日志级别为 INFO[^3]。
#### 4. 编写日志代码
通过 SLF4J API 记录日志可以保持灵活性,并允许切换不同的底层实现而不修改业务逻辑代码。下面是一个简单的例子:
```java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExampleService {
private static final Logger logger = LoggerFactory.getLogger(ExampleService.class);
public void performTask() {
logger.info("This is an info message.");
try {
// Simulate some operation that might throw exceptions.
int result = 1 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
logger.error("An error occurred during task execution.", e);
}
}
}
```
以上代码展示了如何利用 SLF4J 和 Log4j2 输出不同级别的日志消息。
---
阅读全文
相关推荐



















