springboot报错log4j-slf4j-impl cannot be present with log4j-toslf4j

使用gradle开发pulsar程序

使用springboot的stater来创建pulsar服务应用,启动的时候报错了,来问一下copilot image.png 具体返回如下所示:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
This error occurs because both `log4j-slf4j2-impl` and `log4j-to-slf4j` are present in your classpath, which creates a conflict. These two dependencies are incompatible and cannot coexist. Here's how you can resolve this issue:

1. **Remove One of the Dependencies**:
   - If you want to use Log4j2 as your logging framework, remove `log4j-to-slf4j` from your dependencies.
   - If you prefer SLF4J with another backend (e.g., Logback), remove `log4j-slf4j2-impl`.

   In your `pom.xml` (for Maven), exclude the conflicting dependency:
   ```xml
   <dependency>
       <groupId>org.apache.logging.log4j</groupId>
       <artifactId>log4j-to-slf4j</artifactId>
       <scope>runtime</scope>
   </dependency>
  1. Check Transitive Dependencies: Use the mvn dependency:tree command (for Maven) or gradle dependencies (for Gradle) to identify which dependencies are pulling in the conflicting libraries. Exclude them as needed.

  2. Ensure Consistent Logging Framework: Decide on a single logging framework for your project and ensure all dependencies align with it. For example:

    • Use log4j-slf4j2-impl if you’re using Log4j2.
    • Use logback-classic if you’re using SLF4J with Logback.
  3. Clean and Rebuild: After making changes, clean and rebuild your project to ensure the changes take effect:

    1
    
    mvn clean install
    

    or

    1
    
    ./gradlew clean build
    

Let me know if you need further assistance! 😊

那么为什么这两个服务不能同时存在了。 log4j-slf4j-impllog4j-to-slf4j 不能同时存在的原因在于,它们的功能是相互冲突的。以下是具体的分析:

  1. 它们的定义和功能

    • log4j-slf4j-impl:这是 Log4j2 对 SLF4J 接口的实现,允许你使用 SLF4J API 调用 Log4j2 的日志功能。
    • log4j-to-slf4j:这是一个适配器,它将 Log4j2 的日志 API 适配到 SLF4J 的实现,比如 Logback。
  2. 冲突原因

    • 如果这两个包同时存在,日志系统会进入一个“循环依赖”的状态:
      • log4j-slf4j-impl 试图通过 SLF4J 将日志事件路由到 Log4j2。
      • log4j-to-slf4j 试图将 Log4j2 的日志事件再次适配回 SLF4J。
    • 这种循环适配会导致系统无法明确选择日志框架,因此抛出异常并终止运行。
  3. 解决方案: 根据你的项目需求,选择一种方式来统一日志实现:

    • 使用 Log4j2:保留 log4j-slf4j-impl,并排除 log4j-to-slf4j
    • 使用其他 SLF4J 实现(如 Logback):保留 log4j-to-slf4j,并排除 log4j-slf4j-impl

    示例(基于 Gradle 配置):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    // 如果选择 Log4j2
    implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.20.0") {
        exclude(group = "org.apache.logging.log4j", module = "log4j-to-slf4j")
    }
    
    // 如果选择 Logback
    implementation("org.apache.logging.log4j:log4j-to-slf4j:2.20.0") {
        exclude(group = "org.apache.logging.log4j", module = "log4j-slf4j-impl")
    }
    

image.png 这里本项目解决的方法,是把springboot-starter-pulsar 和springboot-starter-web中的spring-boot-starter-logging都去掉了。注意必须两个都要去掉,否则还是会报错这个。

Licensed under CC BY-NC-SA 4.0
最后更新于 Apr 11, 2025 07:19 UTC
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计
Caret Up