Org.apache.logging.log4j.loggingexception: log4j-slf4j-impl cannot be present with log4j-to-slf4j

org.apache.logging.log4j.LoggingException: log4j-slf4j-impl cannot be present with log4j-to-slf4j

This exception occurs when you have both the log4j-slf4j-impl and log4j-to-slf4j dependencies in your project’s classpath. These dependencies are both used to bridge log4j logging framework to the SLF4J (Simple Logging Facade for Java) framework. However, they are incompatible with each other and should not be used together.

The log4j-slf4j-impl library is used to redirect log4j logging calls to SLF4J, while the log4j-to-slf4j library is used to redirect SLF4J calls to log4j. By including both of these dependencies, you are essentially creating a circular dependency between log4j and SLF4J, resulting in this exception.

To resolve this issue, you need to identify which dependency is required for your project and exclude the conflicting one. Here are a couple of examples to illustrate this:

Example 1: Excluding log4j-slf4j-impl

<dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.0</version>
    </dependency>
    <!-- Exclude the log4j-slf4j-impl dependency -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.17.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>
    

Example 2: Excluding log4j-to-slf4j

<dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.0</version>
    </dependency>
    <!-- Exclude the log4j-to-slf4j dependency -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>log4j-to-slf4j</artifactId>
        <version>2.17.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>
    

In both examples, we exclude the conflicting dependency using the “exclusion” tag within the respective dependency declaration. This ensures that only one of the log4j-slf4j-impl or log4j-to-slf4j dependencies is present in the project’s classpath.

Make sure to replace the versions in the dependency declarations with the appropriate versions required by your project.

Read more

Leave a comment