淵源
Logback 為log4j作者推出又一個日志框架我纪,更好的實現(xiàn)了slf4j規(guī)范吩案。
SLF4J 全稱 Simple Logging Facade for Java。Facade 是一種設(shè)計模式虚吟,中文的一種翻譯叫做 門面模式羔挡,可以類比為那句經(jīng)典的,沒有問題是加一層所不能解決的(大意伍茄,原話記不清了栋盹。。敷矫。例获。)』龋總結(jié)起來講就是slf4j本身并沒有提供日志記錄的功能躏敢,僅僅是提供一個標(biāo)準(zhǔn),具體的功能實現(xiàn)由具體的日志框架實現(xiàn)整葡。詳細(xì)的介紹見鏈接 https://www.slf4j.org/
環(huán)境設(shè)置
- 示例編輯環(huán)境使用idea
- 日志實現(xiàn)框架采用 logback
- 依賴管理采用maven
<dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> </dependencies>
源碼分析
示例代碼如下
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Slf4jTest {
private static final Logger logger = LoggerFactory.getLogger(Slf4jTest.class);
public static void main(String[] args) {
logger.info("slf4j");
}
}
代碼分析
//日志打印件余,日志功能實現(xiàn),本次分析重點是初始化過程遭居,并非具體日志打印功能實現(xiàn)
logger.info("slf4j");
//變量的初始化部分啼器,本文關(guān)注的重點部分
private static final Logger logger = LoggerFactory.getLogger(Slf4jTest.class);
LoggerFactory.getLogger 方法一步步點進(jìn)去(ctrl+alt+b,如果出現(xiàn)多個實現(xiàn)類的情況俱萍,則選擇包名包含logback的進(jìn)入)直到
/**
* Return a logger named according to the name parameter using the statically
* bound {@link ILoggerFactory} instance.
*
* @param name The name of the logger.
* @return logger
*/
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
發(fā)現(xiàn)出現(xiàn)一個Factory方法(getILoggerFactory)端壳,開始重點分析該方法實現(xiàn),查看getILoggerFactory方法實現(xiàn)枪蘑,代碼如下:
/**
* Return the {@link ILoggerFactory} instance in use.
* <p/>
* <p/>
* ILoggerFactory instance is bound with this class at compile time.
*
* @return the ILoggerFactory instance in use
*/
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");
}
開始分析getILoggerFactory方法损谦,先拋出以下問題:
- INITIALIZATION_STATE 初始化的位置在哪?初始狀態(tài)是什么岳颇?值是在哪里進(jìn)行更新的照捡?
- FAILED_INITIALIZATION , SUCCESSFUL_INITIALIZATION 等在哪里定義?都有哪些话侧?含義是什么栗精?
- performInitialization 方法執(zhí)行了哪些操作?
- NOP_FALLBACK_FACTORY , TEMP_FACTORY 又是什么東西?
- StaticLoggerBinder.getSingleton().getLoggerFactory(); 這句代碼做了什么見不得人的事情悲立?
1.INITIALIZATION_STATE 初始化的位置在哪鹿寨?初始狀態(tài)是什么?值是在哪里進(jìn)行更新的薪夕?
static int INITIALIZATION_STATE = UNINITIALIZED;
可以看出來 變量 INITIALIZATION_STATE 初始值為 UNINITIALIZED脚草,字面含義是未被初始化狀態(tài)。getILoggerFactory方法首先進(jìn)行判斷寥殖,如果 INITIALIZATION_STATE 值為 未初始化狀體玩讳,先設(shè)置INITIALIZATION_STATE 狀態(tài)為 初始化進(jìn)行中狀態(tài)(ONGOING_INITIALIZATION ),然后執(zhí)行具體初始化操作嚼贡,猜測在performInitialization()方法執(zhí)行的過程中很有可能更新該值的操作。
2. FAILED_INITIALIZATION , SUCCESSFUL_INITIALIZATION 等在哪里定義同诫,含義是什么粤策?都有哪些?
static final int UNINITIALIZED = 0;
static final int ONGOING_INITIALIZATION = 1;
static final int FAILED_INITIALIZATION = 2;
static final int SUCCESSFUL_INITIALIZATION = 3;
static final int NOP_FALLBACK_INITIALIZATION = 4;
很明顯這些類型的變量的創(chuàng)建是為了標(biāo)識 工廠 初始化狀態(tài)使用的误窖,定義位置在LogFactory 類中叮盘,含義分別為(自上至下) 未被初始化,初始化進(jìn)行中霹俺,初始化失敗柔吼,初始化成功,NOP_FALLBACK_INITIALIZATION(no operation fallback initialization,這個不知道怎么翻譯比較好)丙唧。
3.performInitialization 方法執(zhí)行了哪些操作愈魏?
- 首先看performInitialization 方法實現(xiàn)
private final static void performInitialization() {
bind();
if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
versionSanityCheck();
}
}
- 追蹤bind方法實現(xiàn)
private final static void bind() {
try {
Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
// the next line does the binding
StaticLoggerBinder.getSingleton();
INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
reportActualBinding(staticLoggerBinderPathSet);
emitSubstituteLoggerWarning();
} catch (NoClassDefFoundError ncde) {
String msg = ncde.getMessage();
if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
Util.report("Defaulting to no-operation (NOP) logger implementation");
Util.report("See " + NO_STATICLOGGERBINDER_URL
+ " for further details.");
} else {
failedBinding(ncde);
throw ncde;
}
} catch (java.lang.NoSuchMethodError nsme) {
String msg = nsme.getMessage();
if (msg != null && msg.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) {
INITIALIZATION_STATE = FAILED_INITIALIZATION;
Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
Util.report("Your binding is version 1.5.5 or earlier.");
Util.report("Upgrade your binding to version 1.6.x.");
}
throw nsme;
} catch (Exception e) {
failedBinding(e);
throw new IllegalStateException("Unexpected initialization failure", e);
}
}
...未完待續(xù)
一天寫一點,給自己加油>_<