SpringBoot 集成 Log4j2 日志框架


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.xmllog4j2.jsonlog4j2.yaml(默认查找 log4j2.xml)。
  • 路径优先级classpath:(如 src/main/resources) > 系统参数指定路径。
2. 完整配置文件示例(log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值