Spring Boot 集成 Log4j2 日志框架的完整指南
一、为什么选择 Log4j2?
- 高性能:支持异步日志,减少 I/O 阻塞。
- 灵活配置:支持 XML、JSON、YAML 等多种格式。
- 丰富的功能:日志过滤、动态更新配置、多环境适配等。
二、添加依赖与排除默认日志框架
Spring Boot 默认使用 Logback,需排除其依赖并引入 Log4j2:
1. Maven 依赖配置
<!-- pom.xml -->
<dependencies>
<!-- 排除 Spring Boot 默认的 Logback -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入 Log4j2 替代 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
</dependencies>
三、Log4j2 配置文件详解
1. 配置文件类型与优先级
- 支持格式:
log4j2.xml、log4j2.json、log4j2.yaml(默认查找log4j2.xml)。 - 路径优先级:
classpath:(如src/main/resources) > 系统参数指定路径。
2. 完整配置文件示例(log4j2.xml)
<?xml version="1.0" encoding="UTF-8"?>


2366

被折叠的 条评论
为什么被折叠?



