Slf4j class path contains multiple slf4j bindings как исправить

I’m getting the following error. It seems there are multiple logging frameworks bound to slf4j. Not sure how to resolve this. Any help is greatly appreciated.

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/admin/.m2/repository/org/slf4j/slf4j-log4j12/1.6.4/slf4j-log4j12-1.6.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/admin/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.

Yuri's user avatar

Yuri

4,1371 gold badge28 silver badges46 bronze badges

asked Dec 24, 2012 at 18:47

user1493140's user avatar

8

Resolved by adding the following exclusion in the dependencies (of pom.xml) that caused conflict.

<exclusions>
    <exclusion>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </exclusion>
</exclusions> 

answered Mar 25, 2014 at 15:08

user1493140's user avatar

user1493140user1493140

5,9064 gold badges28 silver badges49 bronze badges

5

Gradle version;

configurations.all {
    exclude module: 'slf4j-log4j12'
}

answered Sep 5, 2014 at 22:21

Kerem's user avatar

KeremKerem

2,84723 silver badges35 bronze badges

7

The error probably gives more information like this (although your jar names could be different)

SLF4J: Found binding in
[jar:file:/D:/Java/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in
[jar:file:/D:/Java/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.8.2/log4j-slf4j-impl-2.8.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]

Noticed that the conflict comes from two jars, named logback-classic-1.2.3 and log4j-slf4j-impl-2.8.2.jar.

Run mvn dependency:tree in this project pom.xml parent folder, giving:

dependency tree conflict

Now choose the one you want to ignore (could consume a delicate endeavor I need more help on this)

I decided not to use the one imported from spring-boot-starter-data-jpa (the top dependency) through spring-boot-starter and through spring-boot-starter-logging, pom becomes:

    <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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

in above pom spring-boot-starter-data-jpa would use the spring-boot-starter configured in the same file, which excludes logging (it contains logback)

answered Mar 14, 2018 at 4:19

Tiina's user avatar

TiinaTiina

4,1416 gold badges43 silver badges69 bronze badges

3

Sbt version:

Append exclude("org.slf4j", "slf4j-log4j12") to the dependency that transitively includes slf4j-log4j12. For example, when using Spark with Log4j 2.6:

libraryDependencies ++= Seq(
  // One SLF4J implementation (log4j-slf4j-impl) is here:
  "org.apache.logging.log4j" % "log4j-api" % "2.6.1",
  "org.apache.logging.log4j" % "log4j-core" % "2.6.1",
  "org.apache.logging.log4j" % "log4j-slf4j-impl" % "2.6.1",
  // The other implementation (slf4j-log4j12) would be transitively
  // included by Spark. Prevent that with exclude().
  "org.apache.spark" %% "spark-core" % "1.5.1" exclude("org.slf4j", "slf4j-log4j12")
)

answered Jun 28, 2016 at 11:18

Ruud's user avatar

RuudRuud

3,0783 gold badges38 silver badges50 bronze badges

2

1.Finding the conflicting jar

If it’s not possible to identify the dependency from the warning, then you can use the following command to identify the conflicting jar

mvn dependency: tree

This will display the dependency tree for the project and dependencies who have pulled in another binding with the slf4j-log4j12 JAR.

  1. Resolution

Now that we know the offending dependency, all that we need to do is exclude the slf4j-log4j12 JAR from that dependency.

Ex – if spring-security dependency has also pulled in another binding with the slf4j-log4j12 JAR, Then we need to exclude the slf4j-log4j12 JAR from the spring-security dependency.

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
           <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
    </dependency>

Note – In some cases multiple dependencies have pulled in binding with the slf4j-log4j12 JAR and you don’t need to add exclude for each and every dependency that has pulled in.
You just have to do that add exclude dependency with the dependency which has been placed at first.

Ex –

<dependencies>

        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

</dependencies>

If you work with gradle then add following code to your build.gradle file to exclude SLF4J binding from all the modules

configurations.all {
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

answered Nov 8, 2020 at 16:14

Nafaz M N M's user avatar

Nafaz M N MNafaz M N M

1,4812 gold badges22 silver badges37 bronze badges

I just ignored/removed that jar file.

enter image description here

answered Jul 14, 2016 at 20:53

nobody's user avatar

nobodynobody

10.9k8 gold badges43 silver badges62 bronze badges

<!--<dependency>-->
     <!--<groupId>org.springframework.boot</groupId>-->
     <!--<artifactId>spring-boot-starter-log4j2</artifactId>-->
<!--</dependency>-->

I solved by delete this:spring-boot-starter-log4j2

Nicholas K's user avatar

Nicholas K

15.1k7 gold badges31 silver badges57 bronze badges

answered Aug 30, 2018 at 2:53

Gank's user avatar

GankGank

5,4194 gold badges49 silver badges45 bronze badges

1

Just use only required dependency, not all :))). For me, for normal work of logging process you need this dependency exclude others from pom.xml

<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.8</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.8</version>
    </dependency>

answered Dec 30, 2016 at 8:13

Musa's user avatar

MusaMusa

2,59626 silver badges25 bronze badges

This is issue because of StaticLoggerBinder.class class belongs to two different jars. this class references from logback-classic-1.2.3.jar and same class also referenced from log4j-slf4j-impl-2.10.0.jar. both of jar in classpath. Hence there is conflict between them.
This is reason of log file is not generation even though log4j2.xml file in classpath [src/main/resource].

We have so select one of jar, I recommend use log4j-slf4j-impl-2.10.0.jar file and exclude logback-classic-1.2.3.jar file.
Solution: open pom file and view the dependency Hierarchy [eclipse] or run
mvn dependency:tree command to find out the dependency tree and source of dependency that download the dependency. find the conflicting dependency and exclude them. For Springboot application try this.

<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>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

This is working fine for me after struggling a lots.

answered Jun 3, 2019 at 11:03

Rajeev Rathor's user avatar

org.codehaus.mojo
cobertura-maven-plugin
2.7
test

ch.qos.logback
logback-classic

tools
com.sun

## I fixed with this

org.codehaus.mojo
cobertura-maven-plugin
2.7
test

ch.qos.logback
logback-classic

tools
com.sun

answered Apr 27, 2018 at 9:43

pradeep charan jadi's user avatar

For me, it turned out to be an Eclipse/Maven issue after switch from log4j to logback. Take a look into your .classpath file and search for the string "log4j".

In my case I had the following there:

<classpathentry kind="var" path="M2_REPO/org/slf4j/slf4j-log4j12/1.7.1/slf4j-log4j12-1.7.1.jar"/>
<classpathentry kind="var" path="M2_REPO/log4j/log4j/1.2.17/log4j-1.2.17.jar" />

Removing those entries from the file (or you could regenerate it) fixed the issue.

answered Aug 20, 2018 at 19:37

helmy's user avatar

helmyhelmy

8,9383 gold badges32 silver badges31 bronze badges

For me the answer was to force a Maven rebuild. In Eclipse:

  1. Right click on project-> Maven -> Disable Maven nature
  2. Right click on project-> Spring Tools > Update Maven Dependencies
  3. Right click on project-> Configure > Convert Maven Project

answered Mar 18, 2019 at 13:43

DS.'s user avatar

DS.DS.

5942 gold badges5 silver badges23 bronze badges

1

I solved this by going to Project Structure from my Intellij project.
I deleted the file named: Maven: org.apache.logging.log4j:log4j-to-slf4j-impl:2.14.1
enter image description here

This file is not shown in this picture. You may see two libraries mentioned as log4j-to-slf4j. Delete one and you are good to go.

answered Jan 27, 2022 at 4:59

Raihanul Alam Hridoy's user avatar

For all those looking for the solution for spring-boot-type dependencies, the magic incantation for Gradle is this:

configurations.all {
    exclude group: 'ch.qos.logback', module: 'logback-classic'
}

in your build.gradle at the top level (not inside the dependencies block).

All other solutions found in the interwebs (including the one here suggesting to exclude the slf4j module) did not work for me.

This is what I have in my build.gradle (snippet):


// Removes the annoying warning about the multiple SLF4J implementations:
//    SLF4J: Class path contains multiple SLF4J bindings.
configurations.all {
    exclude group: 'ch.qos.logback', module: 'logback-classic'
}

dependencies {
    annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"

    implementation ('org.springframework.boot:spring-boot-starter-actuator')
    implementation ('org.springframework.boot:spring-boot-starter-data-mongodb-reactive')
    implementation ('org.springframework.boot:spring-boot-starter-webflux')

    annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
    compileOnly "org.projectlombok:lombok:${lombokVersion}"

    // Removes the annoying warning:
    // warning: unknown enum constant When.MAYBE
    //  reason: class file for javax.annotation.meta.When not found
    // See: https://stackoverflow.com/questions/29805622/could-not-find-or-load-main-class-org-gradle-wrapper-gradlewrappermain/31622432
    implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'

    // other stuff...

YMMV

answered Jun 29, 2022 at 21:20

Marco Massenzio's user avatar

Marco MassenzioMarco Massenzio

2,7821 gold badge25 silver badges37 bronze badges

I had the same problem. In my pom.xml i had both

 <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.28</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>

When i deleted the spring-boot-starter-web dependency, problem was solved.

answered Nov 10, 2019 at 12:43

Anna Gaitanidi's user avatar

I got this issue in a non-maven project, two depended jar each contained a slf4j. I solved
by remove one depended jar, compile the project(which of course getting failure) then add the removed one back.

answered Sep 25, 2020 at 13:16

Alan Ackart's user avatar

In case these logs are the result of this fix:
https://stackoverflow.com/a/9919375/2894819

When one of your libraries actually use it. And your application doesn’t need SL4J just replace implementation to runtimeOnly.

// contains dependency to sl4j-api
implementation("com.github.doyaaaaaken:kotlin-csv-jvm:1.2.0")

// add this to remove both warnings
runtimeOnly("org.slf4j:slf4j-nop:1.7.36")

In that case when you run your app the actual dependency will be included once by the library and won’t be included to the bundle of your application.jar itself.

answered Apr 4, 2022 at 7:17

AnoDest's user avatar

AnoDestAnoDest

3331 gold badge3 silver badges13 bronze badges

In my case I had 2 sources of dependencies for log4 one in C:Program Filessmcf.ear directory and the second from maven which caused the multiple binding for sl4j.

Deleting the smcf.ear directory solved the issue for me.

answered May 6, 2022 at 14:50

Shay Ribera's user avatar

Shay RiberaShay Ribera

3244 silver badges17 bronze badges

I’ve a similar problem but using maven-surefire-plugin:

[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ my-api --- 
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
SLF4J: Class path contains multiple
SLF4J providers. SLF4J: Found provider [org.slf4j.nop.NOPServiceProvider@2a32d6c]
SLF4J: Found provider [org.slf4j.jul.JULServiceProvider@7692d9cc]
SLF4J: See https://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual provider is of type [org.slf4j.nop.NOPServiceProvider@2a32de6c]

And after run mvn dependency:tree I find the problem:

[INFO] +- org.apache.maven.plugins:maven-surefire-plugin:jar:2.22.2:test
[INFO] |  - org.apache.maven.surefire:maven-surefire-common:jar:2.22.2:test
[INFO] |     +- org.apache.maven:maven-plugin-api:jar:2.2.1:test
[INFO] |     +- org.apache.maven.plugin-tools:maven-plugin-annotations:jar:3.5.2:test
[INFO] |     +- org.apache.maven.surefire:surefire-api:jar:2.22.2:test
[INFO] |     |  - org.apache.maven.surefire:surefire-logger-api:jar:2.22.2:test
[INFO] ...
[INFO] |     |  +- org.apache.maven.wagon:wagon-webdav-jackrabbit:jar:1.0-beta-6:test
[INFO] |     |  |  +- org.apache.jackrabbit:jackrabbit-webdav:jar:1.5.0:test
[INFO] |     |  |  |  - org.apache.jackrabbit:jackrabbit-jcr-commons:jar:1.5.0:test
[INFO] |     |  |  - org.slf4j:slf4j-nop:jar:2.0.7:test
[INFO] |     |  +- org.slf4j:slf4j-jdk14:jar:2.0.7:test
[INFO] |     |  +- org.slf4j:jcl-over-slf4j:jar:2.0.7:test

The package org.slf4j:slf4j-jdk14 is the cause and not slf4j-api or slf4j-log4j12.

After exclude slf4j-jdk14 dependency the problem is resolved:

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Now the build is clean without warnings:

[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ my-api ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running HexagonalTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] Time elapsed: 2.69 s - in MyTest
[INFO]
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ...
[INFO] -------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -------------------------------------------------------
[INFO] Total time:  8.888 s
[INFO] Finished at: 2023-05-08T13:08:26-03:00
[INFO] -------------------------------------------------------

Reference:

  • slf4j version conflict while building with Maven

answered 2 days ago

ℛɑƒæĿᴿᴹᴿ's user avatar

ℛɑƒæĿᴿᴹᴿℛɑƒæĿᴿᴹᴿ

4,7933 gold badges38 silver badges57 bronze badges

The combination of <scope>provided</scope> and <exclusions> didn’t work for me.

I had to use this:

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <scope>system</scope>
    <systemPath>${project.basedir}/empty.jar</systemPath>
</dependency>

Where empty.jar is a jar file with literally nothing in it.

answered Oct 3, 2019 at 5:38

Alex R's user avatar

Alex RAlex R

11.2k13 gold badges96 silver badges175 bronze badges

Seems removing .m2 directory and :

mvn install -DskipTests -T 4 resolved this issue for me.

fandro's user avatar

fandro

4,7437 gold badges40 silver badges61 bronze badges

answered Oct 7, 2015 at 18:42

bhavin brahmkshatriya's user avatar

0

In this post,we will see about SLF4J: Class Path Contains Multiple SLF4J Bindings.

Using maven

If you are looking for quick solution for this issue, you need to find out how log4j is present on your path.
run mvn dependency:tree and figure out the maven dependency and exclude log4j with snippet below to that dependency in your pom.xml.

<exclusions>

    <exclusion>

        <groupId>org.slf4j</groupId>

        <artifactId>slf4jlog4j12</artifactId>

    </exclusion>

</exclusions>

This should resolve SLF4J: Class Path Contains Multiple SLF4J Bindings.

Using gradle

If you are using gradle, you need to use following code to exclude following dependency.

configurations.all {

    exclude module: ‘slf4j-log4j12’

}

I have provided example below to figure out the dependency from which you should exclude log4j dependency.

Understand the warning

Let’s first understand the warning.

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/apple/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/apple/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.1/log4j-slf4j-impl-2.13.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

It simply says ClassPath contains multiple SLF4J bindings i.e logback-classic-1.2.3.jar and log4j-slf4j-impl-2.13.1.jar.

To understand the warning, we need to understand about SLF4J.

The Simple Logging Facade for Java (SLF4J) provides simple abstraction or facade for various logging frameworks such as log4j, logback, and java.util.logging etc. and it allows the end-user to plug-in the desired logging framework at deployment time.

SLF4J looks for bindings on the classpath to plugin logging framework. If more than one binding is present on the classpath, it will give a warning.

Please note that this is just a warning, not an error, it will pick one of the binding and will go ahead with it.

For example:
SLF4J has chosen logback in above warning. You can have a look at this line.

SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

We need to find a conflicting jars to find root cause of the warning.

You can use the following command to trace the conflicting jar.

[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.2.2.RELEASE:compile
[INFO] | +- org.springframework.boot:spring-boot-starter:jar:2.2.2.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-starter-logging:jar:2.2.2.RELEASE:compile
[INFO] | | | +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] – org.apache.logging.log4j:log4j-slf4j-impl:jar:2.13.1:compile

As you can see, we have two slf4j bindings here.

  • ch.qos.logback:logback-classic:jar
  • org.apache.logging.log4j:log4j-slf4j-impl:jar

logback-classic is transitive dependency, fetched due to spring-boot-starter-web. We have added explicitly log4j-slf4j-impl to use log4j in our project.

To avoid this warning, we need to exclude the unwanted dependencies in pom.xml.
In this example, I have excluded logback-classic.

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>

                <exclusion>

                    <groupId>ch.qos.logback</groupId>

                    <artifactId>logback-classic</artifactId>

                </exclusion>

                <exclusion>

                    <groupId>org.apache.logging.log4j</groupId>

                    <artifactId>log4j-to-slf4j</artifactId>

                </exclusion>

            </exclusions>

        </dependency>

Update the maven project and run the application. You should not get SLF4J Warning: Class Path Contains Multiple SLF4J Bindings now.

Reference

SLF4J: class path contains multiple SLF4J bindings.

That’s all about SLF4J: Class Path Contains Multiple SLF4J Bindings.

Class path contains multiple SLF4J bindings is a warning message from the SLF4J library when your project has different SLF4J bindings for the same logging framework in the “$CLASSPATH”.Class Path Contains Multiple slf4j Bindings

This article will explain factors that will lead to this warning message, and we’ll teach you methods that can resolve it in your coding environment. From what you’ll learn in the upcoming sections, you’ll learn how to remove multiple slf4j bindings, and you’ll feel confident that you can solve the warning if you see it again.

Now, switch to your IDE, and let’s save you precious debugging time that you can use for something productive.

Contents

  • Why Do You See the Warning About Multiple slf4j Bindings?
    • – Your Project Has Different Versions of Slf4j
  • How To Solve the Multiple slf4j Bindings Warning?
    • – Exclude the Conflicting slf4j Library in Your Build Process
    • – Set the Order of the Class Path Elements
    • – Specify the Classpath Using the “-Cp” or “-Classpath” Option
    • – Enforce a Single slf4j Using “Maven-enforcer-Plugin
    • – Use “Resolutionstrategy” To Force a Version of Slf4j
  • Conclusion

Why Do You See the Warning About Multiple slf4j Bindings?

You see the warning about multiple SLF4J bindings because your project has different versions of the SLF4J library in the “$CLASSPATH”. This can happen when multiple dependencies pull in their version of SLF4J, and this can cause conflicts and compatibility issues.

– Your Project Has Different Versions of Slf4j

When your project has different versions of the SLF4J library in the class path, that’s when you’ll see the “class path contains multiple slf4j bindings spring-boot” warning. The major cause of this is when your project has multiple dependencies, and each of these dependencies has its version of SLF4J.

This will lead to a wrong class path order and compatibility issues because SLF4J can select another binding and send your logging to another logging framework, causing confusion. For example, if you have two dependencies in your project, one that uses SLF4J version “1.7.25” and another that uses SLF4J version “1.7.26”, this can lead to the warning.Warning About Multiple slf4j Bindings

The warning happens because when your application runs, both versions of the SLF4J library will be loaded into the class path. With this, the Java Virtual Machine (JVM) may not know which version to use.

Another example is if your logging framework is configured to use Logback and you have included the SLF4J API in your project as a dependency. Logback will automatically include its binding for SLF4J, and you’ll see the warning if you have another logging framework that includes its binding for SLF4J.

How To Solve the Multiple slf4j Bindings Warning?

To solve the multiple SLF4J bindings warning, you can exclude the conflicting SLF4J library in your build process via the “pom.xml” or “build.gradle”. And if you are running your application from the command line, you can specify the class path using the “-cp” or “-classpath” option.

Additionally, you can set the order of the class path elements or enforce a single SLF4J using the “maven-enforcer-plugin”. Finally, if Gradle is your build system, use “resolutionStrategy” to force a specific version of SLF4J.

– Exclude the Conflicting slf4j Library in Your Build Process

The exclusion of the conflicting SLF4J library in your build process is how you solve the “class path contains multiple slf4j bindings maven” warning message. Before you exclude it, you’ll need to identify the conflicting SLF4J library using the Maven dependency tree.

The latter will display the hierarchical view of your project’s dependencies, including their transitive dependencies and their version numbers. From this, you can see duplicate libraries in your project, and you can exclude them in the “pom.xml” file.

Now to use the Maven dependency tree, use the following steps:

  1. Open a terminal or command prompt and navigate to the root directory of your Maven project.
  2. Run the following command (without quotes): “mvn dependency:tree”
  3. Examine the output of the previous command and look for any SLF4J library dependencies with different versions that may be causing the error.
  4. Exclude any duplicate or conflicting dependencies from your build configuration by adding an exclusion to the relevant dependency in your “pom.xml” file.

For example, in the following XML file, the “slf4j-api” dependency is excluded from the “slf4j-log4j12” dependency. This ensures that only one version of the SLF4J library is included in the project’s class path. Also, you can use the same approach to solve the “systemerr r slf4j: class path contains slf4j bindings” in Tomcat or Spring Boot.

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-log4j12</artifactId>

<version>1.7.30</version>

<exclusions>

<exclusion>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

</exclusion>

</exclusions>

</dependency>

– Set the Order of the Class Path Elements

In the context of resolving the “multiple SLF4J bindings” warning, you can adjust the class path order by using the maven-surefire-plugin to set the order of the class path elements. This will exclude unwanted versions of the SLF4J library from the class path during test execution.

You can do this by adding exclusion rules to the plugin configuration in your project’s “pom.xml” file. For example, to exclude version “1.7.26” of the SLF4J library, you can add the following configuration to the Surefire plugin:

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>3.0.0-M9</version>

<configuration>

<classpathDependencyExcludes>

<classpathDependencyExclude>org.slf4j:slf4j-api:1.7.26</classpathDependencyExclude>

</classpathDependencyExcludes>

</configuration>

</plugin>

<plugins>

<plugin>

– Specify the Classpath Using the “-Cp” or “-Classpath” Option

A solution to the “slf4j: class path contains multiple slf4j bindings pyspark” warning is to explicitly set the class path in your application’s startup script or command. This is a perfect solution for you if you’re running your application from the command line because you can avoid conflicts with other versions of the SLF4J library.

To set the class path, use the “-cp” or “-classpath” option as follows:

java -cp /path/to/correct/slf4j-version.jar:/path/to/other/libs my.package.MainClass

From the command above, note the following:

  • The “-cp” flag is used to specify the classpath
  • The “/path/to/correct/slf4j-version.jar” directory contains the correct version of the SLF4J library that your application needs.
  • The “/path/to/other/libs” directory contains any other libraries that your application needs to run.

Finally, if Eclipse is your IDE, you can solve the “class path contains multiple slf4j bindings. eclipse” warning by removing the SLF4J binding from your project’s class path. You do this using the following: “YourProject > Properties > Java Build Path > Libraries > Select the SLF4J Binding JAR and hit ‘Remove’”.

– Enforce a Single slf4j Using “Maven-enforcer-Plugin

A tool that will solve the “class path contains multiple slf4j bindings” warning is the Maven Enforcer Plugin. You can also use this plugin to ensure that your project includes only one version of the SLF4J library.

To do this, you’ll configure the plugin to fail the building process if multiple versions of the library are detected in your project’s dependencies.Solve the Multiple slf4j Bindings Warning

For example, the following configuration in your “pom.xml” file tells the Maven Enforcer Plugin to enforce the use of the “1.7.30” version of the SLF4J library:

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-enforcer-plugin</artifactId>

<version>3.0.0-M3</version>

<executions>

<execution>

<id>enforce-single-slf4j</id>

<goals>

<goal>enforce</goal>

</goals>

<configuration>

<rules>

<requireDependencyVersion>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>1.7.30</version>

<message>Multiple versions of SLF4J found in project dependencies!</message>

</requireDependencyVersion>

</rules>

</configuration>

</execution>

</executions>

</plugin>

</plugins>

</build>

– Use “Resolutionstrategy” To Force a Version of Slf4j

If Gradle is your build tool, you can use the “resolutionStrategy” block in “build.gradle” to force a specific version of the SLF4J library. This will solve the “class path contains multiple slf4j bindings gradle IntelliJ warning and get you back on track. Before this, you can use Gradle dependency insight to identify the conflicting SLF4J library:

./gradlew dependencyInsight –dependency slf4j-api

The output of the previous command will allow you to identify which dependencies are causing the conflict. Once you have identified the conflicting dependencies, you can use the “resolutionStrategy” block in the “build.gradle” file to force a specific version of the SLF4J library.

For example, if you want to force version “1.7.30” of the SLF4J library, you can add the following block to your “build.gradle” file:

configurations.all {

resolutionStrategy {

force ‘org.slf4j:slf4j-api:1.7.30’

}

}

Conclusion

This article explains why you see multiple SLF4J bindings in a class path and five methods to resolve it for you. As you move on to your daily activities, hold on to the following:

  • You’ll see the “class path contains multiple SLF4J bindings” if there are multiple bindings for the same logging framework in the class path.
  • You can solve the multiple SLF4J bindings warning by excluding the conflicting SLF4J library from your build process.
  • To exclude an SLF4J library in Maven, identify the conflicting library using the “mvn dependency:tree” command and it to the “<exclusion>” block in “pom.xml”.
  • The “maven-enforcer-plugin” and the “resolutionStrategy” in Gradle are ways to ensure that your project uses a specific version of SLF4J.
  • To solve the “class path contains multiple slf4j bindings docker” warning, you can also exclude the conflicting SLF4J library in “build.gradle” or “pom.xml”.

Now, you should feel good because you have lots of methods that will fix the “multiple SLF4J bindings” warning messages. Have fun, and don’t forget to share our article.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

В этой главе мы обсудим различные сообщения об ошибках или предупреждения, которые мы получаем при работе с SLF4J, и причины / значения этих сообщений.

Не удалось загрузить класс “org.slf4j.impl.StaticLoggerBinder”.

Это предупреждение, которое вызывается, если в пути к классам нет привязок SLF4J.

Ниже приводится полное предупреждение –

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
details.

Чтобы решить эту проблему, необходимо добавить одну из привязок каркаса ведения журнала. Это объясняется в главе Hello World этого урока.

Примечание. Это происходит в версиях SLF4J между 1.6.0 и 1.8.0-бета2.

Поставщики SLF4J не найдены

В slf4j-1.8.0-beta2 вышеупомянутое предупреждение более ясно говорит, что «поставщики SLF4J не были найдены» .

Ниже приводится полное предупреждение –

SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.

Classpath содержит привязки SLF4J для версий slf4j-api до 1.8

Если вы используете версию SLF4J 1.8 и у вас есть привязки предыдущих версий в classpath, но не привязки 1.8, вы увидите предупреждение, как показано ниже.

SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to
1.8.
SLF4J: Ignoring binding found at
[jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/
slf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation.

NoClassDefFoundError: org / apache / commons / logging / LogFactory

Если вы работаете с slf4j-jcl и у вас есть только slf4j-jcl.jar в вашем пути к классам, вы получите исключение, такое как приведенное ниже.

Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/logging/LogFactory
   at org.slf4j.impl.JCLLoggerFactory.getLogger(JCLLoggerFactory.java:77)
   at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358)
   at SLF4JExample.main(SLF4JExample.java:8)
Caused by: java.lang.ClassNotFoundException:
org.apache.commons.logging.LogFactory
   at java.net.URLClassLoader.findClass(Unknown Source)
   at java.lang.ClassLoader.loadClass(Unknown Source)
   at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
   at java.lang.ClassLoader.loadClass(Unknown Source)
   ... 3 more

Чтобы решить эту проблему, вам нужно добавить commons-logging.jar к вашему classpath.

Обнаружил как jcl-over-slf4j.jar, так и связанный slf4j-jcl.jar на пути к классам.

Привязка slf4j-jcl.jar перенаправляет вызовы регистратора slf4j в JCL, а jcl-over-slf4j.jar перенаправляет вызовы регистратора JCL в slf4j. Таким образом, вы не можете иметь оба в classpath вашего проекта. Если вы сделаете это, вы получите исключение, такое как приведенное ниже.

SLF4J: Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class
path, preempting StackOverflowError.
SLF4J: See also http://www.slf4j.org/codes.html#jclDelegationLoop for more
details.
Exception in thread "main" java.lang.ExceptionInInitializerError
   at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:71)
   at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:42)
   at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
   at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
   at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
   at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
   at SLF4JExample.main(SLF4JExample.java:8)
Caused by: java.lang.IllegalStateException: Detected both jcl-over-slf4j.jar
AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. See
also http://www.slf4j.org/codes.html#jclDelegationLoop for more details.
   at org.slf4j.impl.JCLLoggerFactory.<clinit>(JCLLoggerFactory.java:54)
   ... 7 more

Чтобы решить эту проблему, удалите любой из файлов JAR.

Обнаружено несоответствие имени регистратора

Вы можете создать объект Logger с помощью –

  • Передача имени созданного регистратора в качестве аргумента методу getLogger () .

  • Передача класса в качестве аргумента этому методу.

Передача имени созданного регистратора в качестве аргумента методу getLogger () .

Передача класса в качестве аргумента этому методу.

Если вы пытаетесь создать объект фабрики регистратора, передавая класс в качестве аргумента, и если вы установили системное свойство slf4j.detectLoggerNameMismatch в значение true, тогда имя класса, которое вы передаете в качестве аргумента методу getLogger () и используемый вами класс должен быть таким же, в противном случае вы получите следующее предупреждение –

«Обнаружено несоответствие имени регистратора.

Рассмотрим следующий пример.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SLF4JExample {
   public static void main(String[] args) {
      System.setProperty("slf4j.detectLoggerNameMismatch", "true");
      
      //Creating the Logger object
      Logger logger = LoggerFactory.getLogger(Sample.class);

      //Logging the information
      logger.info("Hi Welcome to Tutorilspoint");
   }
}

Здесь мы установили для свойства slf4j.detectLoggerNameMismatch значение true. Имя класса, которое мы использовали, – SLF4JExample, а имя класса, которое мы передали методу getLogger (), – Sample, так как они оба не равны, мы получим следующее предупреждение.

SLF4J: Detected logger name mismatch. Given name: "Sample"; computed name:
"SLF4JExample".
SLF4J: See http://www.slf4j.org/codes.html#loggerNameMismatch for an
explanation
Dec 10, 2018 12:43:00 PM SLF4JExample main
INFO: Hi Welcome to Tutorilspoint

Примечание – это происходит после slf4j 1.7.9

Classpath содержит несколько привязок SLF4J.

У вас должна быть только одна привязка в пути к классам. Если у вас есть несколько привязок, вы получите предупреждение с указанием привязок и их местоположения.

Предположим, что если у нас есть привязки slf4j-jdk14.jar и slf4j-nop.jar в пути к классам, мы получим следующее предупреждение.

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in
[jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/
slf4j-1.7.25/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in
[jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/
slf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
explanation.
SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory]

Обнаружены оба log4j-over-slf4j.jar И привязанные slf4j-log4j12.jar на пути к классам

Чтобы перенаправить вызовы log4j logger в slf4j, вам нужно использовать привязку log4j-over-slf4j.jar, а если вы хотите перенаправить вызовы slf4j в log4j, вам необходимо использовать привязку slf4j-log4j12.jar .

Таким образом, вы не можете иметь оба в classpath. Если вы это сделаете, вы получите следующее исключение.

Это означает, что в проекте подключено более одной реализации SLF4J.

Для исключения ненужной реализации нужно определить с каким пакетом она идет. Это можно сделать при помощи команды mvn dependency:tree.

После того как мы знаем куда входит ненужная реализация SLF4J идем в pom файл и находим dependency с тем пакетом, в который входит ненужная реализация. Далее в этой зависимости вводим исключение с ненужной реализацией (например slf4j-log4j12):

<exclusions>

<exclusion>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-log4j12</artifactId>

</exclusion>

</exclusions>

Обновляем проект.

Готово.

Добавить комментарий