SLF4J: Multiple bindings were found on the class path

众所周知,SLF4J是一个日志门面框架,它的作用是用于定义统一的日志接口,而具体的日志实现是由各个日志框架实现的,比如log4j,logback等。

问题

在使用SLF4J时,当class path同时包含了多个日志框架时,将会导致日志无法按照预期打印输出。通过查看控制台日志,能发现输出的warning info: Multiple bindings were found on the class path。

解决方法

当类路径中有多个日志框架可用时,应只保留一个日志框架,删除其他日志框架。比如,版本v0.8.1的cassandra-all jar引入了log4j h和slf4j-log4j12这两个编译时依赖项。当在maven pom.xml中引入v0.8.1的cassandra-all jar,实际上同时引入了log4j h和slf4j-log4j12。在这种情况下,如果你不希望使用og4j h和slf4j-log4j12,你可以按照下面的方式排除这两个artifact:

<dependencies>
  <dependency>
    <groupId> org.apache.cassandra</groupId>
    <artifactId>cassandra-all</artifactId>
    <version>0.8.1</version>

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

  </dependency>
</dependencies>

注意:SLF4J发出的警告仅仅是一个警告。虽然发现了多个日志框架,但是SLF4J仍将会选择一个日志框架使用。具体选择哪一个日志框架则由JVM决定。为了实用的目的,它应该被认为是随机的。

Embedded components such as libraries or frameworks should not declare a dependency on any SLF4J binding but only depend on slf4j-api. When a library declares a compile-time dependency on a SLF4J binding, it imposes that binding on the end-user, thus negating SLF4J's purpose. When you come across an embedded component declaring a compile-time dependency on any SLF4J binding, please take the time to contact the authors of said component/library and kindly ask them to mend their ways.

内嵌式组件,比如类库或框架,不应该声明除了slf4j-api之外的任何slf4j日志框架。因为,如果一个类库声明包含了一个编译时依赖项,实际上就把这种绑定强加到终端用户身上了。这违反了SLF4J的目的。

猜你喜欢

转载自my.oschina.net/yqz/blog/1814021