SLF4J不是日誌框架而是一個簡單日誌門面,它的目的是容許最終用戶在部署時使用指望的日誌框架。html
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.java
因此SLF4J在使用時除了自身的jar包外,還須要日誌框架以及適配器。apache
以應用中使用log4j爲例。須要依賴slf4j-api,slf4j-log4j,log4j。api
使用方法:框架
Logger logger = LoggerFactory.getLogger(getClass());spa
實現原理:.net
SLF4J 在編譯時靜態綁定org.slf4j.impl.StaticLoggerBinder,而適配器中必須包含這個類。日誌
LoggerFactory:code
public static ILoggerFactory getILoggerFactory() { if (INITIALIZATION_STATE == UNINITIALIZED) { INITIALIZATION_STATE = ONGOING_INITIALIZATION; performInitialization(); } switch (INITIALIZATION_STATE) { case SUCCESSFUL_INITIALIZATION: return StaticLoggerBinder.getSingleton().getLoggerFactory(); case NOP_FALLBACK_INITIALIZATION: return NOP_FALLBACK_FACTORY; case FAILED_INITIALIZATION: throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); case ONGOING_INITIALIZATION: // support re-entrant behavior. // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
return TEMP_FACTORY; } throw new IllegalStateException("Unreachable code"); } }
SLF4J與Common-Logging的區別orm
Common-Logging是apache提供的一個通用的日誌接口。這兩個日誌門面的功能相似,不一樣的是實現方式不同。SLF4J是經過靜態綁定的方式獲得日誌框架,而Common-Logging是動態查找方式。
Common-Logging 使用方式:Log logger = LogFactory.getLog(getClass());
PS:若是想從Common-logging切換到SLF4J,能夠添加jar包:jcl-over-slf4j,slf4j-api。代碼不須要任何修改。
參考連接:
http://www.slf4j.org/
http://www.360doc.com/content/14/0310/21/12129652_359387856.shtml
http://blog.csdn.net/yycdaizi/article/details/8276265