You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot整合log4j2不加载log4j2.xml 仍使用默认日志问题求助

问题解决步骤

1. 彻底排除Spring Boot默认日志依赖

你当前仅在spring-boot-starter-web中排除了默认日志实现,其他如spring-boot-starter-data-mongodb、spring-boot-starter-aop等启动器仍会间接引入logback依赖,只要classpath中存在logback相关jar包,Spring Boot会优先使用logback作为日志实现,导致log4j2配置不生效。
修改pom.xml,全局排除默认日志:

<dependencies>
    <!-- 新增全局默认日志排除配置,放在所有依赖最前面 -->
    <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>
    <!-- 原有其他依赖保持不变 -->
</dependencies>

2. 强制指定日志配置与实现

在application.properties中添加如下配置,强制Spring Boot识别log4j2配置,避免默认配置覆盖:

# 显式指定log4j2配置文件路径
logging.config=classpath:log4j2.xml
# 强制使用log4j2作为日志系统实现
logging.system=org.springframework.boot.logging.log4j2.Log4J2LoggingSystem

3. 校验依赖冲突

执行maven命令检查是否存在残留的日志相关冲突依赖:

mvn dependency:tree | grep -E 'logback|commons-logging'

如果返回结果中存在上述依赖,逐个在对应依赖节点下添加排除规则即可。

4. 生效配置

清理maven缓存并重新编译启动项目:

mvn clean package

启动后即可看到日志格式匹配你在log4j2.xml中配置的pattern,且debug级别日志正常输出。

内容的提问来源于stack exchange,提问作者mr.Penguin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:36:03