轉:slf4j-api、slf4j-log4j十二、log4j之間關係

1. slf4j-api

slf4j:Simple Logging Facade for Java,爲java提供的簡單日誌Facade。Facade門面,更底層一點說就是接口。它容許用戶以本身的喜愛,在工程中經過slf4j接入不一樣的日誌系統。java

所以slf4j入口就是衆多接口的集合,它不負責具體的日誌實現,只在編譯時負責尋找合適的日誌系統進行綁定。具體有哪些接口,所有都定義在slf4j-api中。查看slf4j-api源碼就能夠發現,裏面除了public final class LoggerFactory類以外,都是接口定義。所以slf4j-api本質就是一個接口定義。apache

它只提供一個核心slf4j api(就是slf4j-api.jar包),這個包只有日誌的接口,並無實現,因此若是要使用就得再給它提供一個實現了些接口的日誌包,比 如:log4j,common logging,jdk log日誌實現包等,可是這些日誌實現又不能經過接口直接調用,實現上他們根本就和slf4j-api不一致,所以slf4j又增長了一層來轉換各日誌實 現包的使用,好比slf4j-log4j12等。api

slf4j+log4j組合使用模式:
1. slf4j-api-1.5.11.jar
2. slf4j-log4j12-1.5.11.jar
3. log4j-1.2.15.jar
4. log4j.properties(也能夠是 log4j.xml)app

具體使用日誌類的API:框架

1. log4j:
import org.apache.log4j.Logger;
Logger logger= Logger.getLogger(xx.class);
2. slf4j+log4j:(推薦)
import  org.slf4j.Logger;
import  org.slf4j.LoggerFactory;
Logger logger = LoggerFactory.getLogger(xx.class);

2. slf4j-api、slf4j-log4j十二、log4j

下圖比較清晰的描述了它們之間的關係,例子爲當系統採用log4j做爲日誌框架實現的調用關係:this

1. 首先系統包含slf4j-api做爲日誌接入的接口:編譯時slf4j-api中public final class LoggerFactor類中private final static void bind()方法會尋找具體的日誌實現類綁定,主要經過StaticLoggerBinder.getSingleton()的語句調用。
2. slf4j-log4j12是連接slf4j-api和log4j中間的適配器:它實現了slf4j-api中StaticLoggerBinder接口,從而使得在編譯時綁定的是slf4j-log4j12的getSingleton()方法。
3. log4j是具體的日誌系統:經過slf4j-log4j12初始化Log4j,達到最終日誌的輸出。spa

Failed to load class org.slf4j.impl.StaticLoggerBinder

This warning message is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jarslf4j-log4j12.jarslf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.日誌

SINCE 1.6.0 As of SLF4J version 1.6, in the absence of a binding, SLF4J will default to a no-operation (NOP) logger implementation.code

If you are responsible for packaging an application and do not care about logging, then placing slf4j-nop.jar on the class path of your application will get rid of this warning message. Note that 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.

意思就是說,解決這個bug須要添加如下任意一個依賴

  • slf4j-nop.jar
  •  slf4j-simple.jar
  •  slf4j-log4j12.jar
  • slf4j-jdk14.jar 
  •  logback-classic.jar

原文:https://www.slf4j.org/codes.html#StaticLoggerBinder

相關文章
相關標籤/搜索