首页 > 解决方案 > Maven SL4J 多重绑定,之前的解决方案失败

问题描述

我有一个具有多个 SLF4J 绑定的项目。我已阅读并尝试了此 SO 帖子其他 SO 帖子slf4j 网站中的解决方案。

如果我在运行代码时看到的是

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/Mike/.m2/repository/org/jlab/coat/coat-libs/5.1-SNAPSHOT/coat-libs-5.1-SNAPSHOT.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/Mike/.m2/repository/org/slf4j/slf4j-log4j12/1.7.16/slf4j-log4j12-1.7.16.jar!/org/slf4j/impl/StaticLoggerBinder.class]

但是在我的 pom.xml 文件中,我已经有了

    <dependency>
        <groupId>org.jlab.coat</groupId>
        <artifactId>coat-libs</artifactId>
        <version>5.1-SNAPSHOT</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

在 mvn 依赖项中:tree 我没有看到排除 jar 的此依赖项,仅适用于 Spark jar,即

[INFO] com.IKP:DCdatabase:jar:0.0.1-SNAPSHOT
[INFO] +- org.jlab.coat:coat-libs:jar:5.1-SNAPSHOT:compile
[INFO] +- org.apache.spark:spark-core_2.11:jar:2.2.1:compile
...
...
...
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.16:compile
[INFO] |  +- org.slf4j:jul-to-slf4j:jar:1.7.16:compile
[INFO] |  +- org.slf4j:jcl-over-slf4j:jar:1.7.16:compile
[INFO] |  +- log4j:log4j:jar:1.2.17:compile
[INFO] |  +- org.slf4j:slf4j-log4j12:jar:1.7.16:compile

我还尝试了更多步骤,例如清理我的 .m2 目录,并从头开始构建所有源,但我仍然看到这种双重绑定。

发生的细微差别是 Spark 的日志抑制确实发生了,即

    Logger.getLogger("org.apache.spark.SparkContext").setLevel(Level.WARN);
    Logger.getLogger("org").setLevel(Level.OFF);
    Logger.getLogger("akka").setLevel(Level.OFF);

不再将级别设置为关闭,我会看到所有级别。

是否有另一种方法可以删除 SLF4J 的多重绑定?

标签: apache-sparkmaven-2slf4j

解决方案


在我看来,它coat-libs已经被打包为一个 uber jar,这就是为什么 slf4j 在你这样做时不会显示为依赖项的原因mvn dependency:tree。这解释了为什么您的排除不起作用。

我建议看一下用于打包 jar 的 maven shade 插件。然后,您可以使用过滤器从使用过滤器的外套库中排除 slf4j 依赖项。

例如,也许是这样的:

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.1.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <filters>
                <filter>
                  <artifact>org.jlab.coat:coat-libs</artifact>
                  <excludes>
                    <exclude>org/slf4j/**</exclude>
                  </excludes>
                </filter>
                <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                  </excludes>
                </filter>
              </filters>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

推荐阅读