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的目的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章