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

Spring Boot中Slf4j+Log4j2日志被Logback依赖阻塞问题

解决Spring Boot中Slf4j绑定Logback而非Log4j2的问题

我完全懂你遇到的这个头疼问题——Spring Boot默认的日志配置确实会优先用Logback,哪怕你想换成Log4j2也会被它“抢风头”。下面给你一步步解决的方案:

1. 替换默认日志依赖

Spring Boot的spring-boot-starter-parent间接引入了spring-boot-starter-logging,这个依赖包里包含了Logback的核心库,这就是Slf4j自动绑定Logback的原因。我们需要把这个默认依赖排除,然后引入Log4j2的官方starter:

在你的项目pom.xml里,找到你引入的Spring Boot starter(比如spring-boot-starter-web),添加排除配置,然后引入spring-boot-starter-log4j2:

<!-- 排除默认的Logback日志依赖 -->
<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>

<!-- 引入Log4j2的Spring Boot starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

这个starter会自动帮你处理Slf4j和Log4j2的绑定,不用手动加一堆零散的依赖。

2. 确保log4j2.json配置文件正确放置

把你的log4j2.json配置文件放在src/main/resources目录下,Spring Boot启动时会自动加载这个文件。注意文件名一定要准确,别写成log4j.json或者其他拼写错误的名字。

3. 验证配置是否生效

  • 先检查Maven依赖树,确认Logback已经被完全排除:
    mvn dependency:tree | grep logback
    
    如果没有任何输出,说明Logback已经从依赖中移除了。
  • 然后在代码里写个简单的日志测试:
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
        private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
    
        @GetMapping("/hello")
        public String hello() {
            logger.info("这是Log4j2输出的日志");
            return "Hello World";
        }
    }
    
    启动应用后访问/hello,看控制台输出是否符合你在log4j2.json里配置的格式,如果是,就说明配置成功了。

为什么直接在父POM排除不生效?

Maven的依赖排除规则是只针对当前依赖的直接子依赖,父POM里的spring-boot-starter-logging是传递依赖,直接在父POM里排除不会生效。必须在你项目中直接引入的starter(比如web starter)里排除它,或者用spring-boot-starter-log4j2来自动替换,这也是Spring Boot官方推荐的做法。

内容的提问来源于stack exchange,提问作者Maiko Kingma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:23:56