如何在构建时阻止SLF4J臭名昭着的“多重绑定”警告?

时间:2014-08-15 23:23:30

标签: java dependencies slf4j

我的程序输出以下恼人的消息:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/scratch/events-beware/events-beware/build/install/events-beware/lib/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/scratch/events-beware/events-beware/build/install/events-beware/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/scratch/events-beware/events-beware/build/install/events-beware/lib/slf4j-simple-1.6.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]

不需要的SLF4J绑定是我项目的传递依赖项,因此我配置我的依赖项管理器以排除包含不需要的绑定的jar。这有效一段时间,直到一个新的依赖项被添加到项目中,这又引入了另一个不需要的绑定......

如果我过度依赖多个SLF4J绑定,如何使用构建系统的强大功能使构建失败?

1 个答案:

答案 0 :(得分:1)

在构建时,您可以检查每个依赖项,寻找SLF4J绑定。如果您找到多个,则可能无法构建。

使用Gradle执行此操作:

task checkSlf4j {
    description 'Ensure only one SFL4j binding is present in the runtime configuration'

    doLast {
        def bindings = []
        configurations.runtime.each {
            zipTree(it).matching { include 'org/slf4j/impl/StaticLoggerBinder.class' }.each { c ->
                bindings << [it.getName(), c]
            }
        }
        if (bindings.size () > 1) {
            throw new GradleException("Multiple SLF4J bindings found: ${bindings*.getAt(0)}")
        }
    }
}

check.dependsOn checkSlf4j

结果如下:

$ ./gradlew build
:bundleJars UP-TO-DATE
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE
:assemble UP-TO-DATE
:checkSlf4j FAILED

FAILURE: Build failed with an exception.

* Where:
Script '/scratch/events-beware/events-beware/slf4j.gradle' line: 14

* What went wrong:
Execution failed for task ':checkSlf4j'.
> Multiple SLF4J bindings found: [logback-classic-1.1.2.jar, slf4j-log4j12-1.6.1.jar, slf4j-simple-1.6.1.jar]

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2.009 secs
相关问题