前言
在日志Logger漫談中提到了slf4j僅僅是作為日志門面存和,給用戶提供統(tǒng)一的API使用脖隶,而真正的日志系統(tǒng)的實現(xiàn)是由logback或者log4j這樣的日志系統(tǒng)實現(xiàn)徙赢,那究竟slf4j是怎樣集成logback或者log4j的呢奥此?
集成logback
前文中提到到腥,如果要使用slf4j+logback,需要引入slf4j-api及l(fā)ogback-classic萌业、logback-core三個jar包坷襟。
- 我們一般這樣使用
Logger logger = LoggerFactory.getLogger("logger1");
logger.info("This is a test msg from: {}", "LNAmp");
- LoggerFactory.getLogger的源代碼如下:
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
需要注意的是,Logger生年、LoggerFactory婴程、ILoggerFactory都是slf4j-api.jar中的類或接口。
從源碼看來抱婉,獲取Logger有兩個過程档叔,現(xiàn)獲取對應(yīng)的ILoggerFactory,再通過ILoggerFactory獲取Logger
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");
}
private final static void performInitialization() {
bind();
if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
versionSanityCheck();
}
}
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);
}
}
獲取ILoggerFactory的過程基本可以分為
- performInitialization() : 完成StaticLoggerBinder的初始化
- getLoggerFactory() :通過StaticLoggerBinder.getSingleton().getLoggerFactory()獲取對應(yīng)的ILoggerFactory
在整個獲取Logger的過程蒸绩,StaticLoggerBinder是個非常重要的類衙四,其對象以單例的形式存在。在performInitialization過程中侵贵,slf4j會首先查找"org/slf4j/impl/StaticLoggerBinder.class"資源文件届搁,目的是為了在存在多個org/slf4j/impl/StaticLoggerBinder.class時給開發(fā)者report警告信息,接著slf4j會使用StaticLoggerBinder.getSingleton()完成StaticLoggerBinder單例對象的初始化窍育。
slf4j之所以能使用StaticLoggerBinder.getSingleton()是因為logback-classic和slf4j-log4j都按照slf4j的規(guī)定實現(xiàn)了各自的org/slf4j/impl/StaticLoggerBinder.class卡睦。那么如果系統(tǒng)中同時存在logback-classic和slf4j-log4j的話,slf4j選擇哪一個呢漱抓,答案是隨機挑選(這是由類加載器決定的表锻,同包同名字節(jié)碼文件的加載先后順序不一定)。
StaticLoggerBinder初始化
logback的StaticLoggerBinder的初始化如下
void init() {
try {
try {
new ContextInitializer(defaultLoggerContext).autoConfig();
} catch (JoranException je) {
Util.report("Failed to auto configure default logger context", je);
}
StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
contextSelectorBinder.init(defaultLoggerContext, KEY);
initialized = true;
} catch (Throwable t) {
// we should never get here
Util.report("Failed to instantiate [" + LoggerContext.class.getName()
+ "]", t);
}
}
其中ContextInitializer會完成配置文件例如logback.xml的文件解析和加載乞娄,特別要注意的是defaultLoggerContext是LoggerContext的實例瞬逊,LoggerContext是logback對于ILoggerFactory的實現(xiàn)。
獲取Logger
public final Logger getLogger(final String name) {
if (name == null) {
throw new IllegalArgumentException("name argument cannot be null");
}
// if we are asking for the root logger, then let us return it without
// wasting time
if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) {
return root;
}
int i = 0;
Logger logger = root;
Logger childLogger = (Logger) loggerCache.get(name);
if (childLogger != null) {
return childLogger;
}
String childName;
while (true) {
int h = Logger.getSeparatorIndexOf(name, i);
if (h == -1) {
childName = name;
} else {
childName = name.substring(0, h);
}
i = h + 1;
synchronized (logger) {
childLogger = logger.getChildByName(childName);
if (childLogger == null) {
childLogger = logger.createChildByName(childName);
loggerCache.put(childName, childLogger);
incSize();
}
}
logger = childLogger;
if (h == -1) {
return childLogger;
}
}
在logback中仪或,ILoggerFactory的實現(xiàn)是LoggerContext确镊,調(diào)用LoggerContext.getLogger獲取的Logger實例類型為ch.qos.logback.classic.Logger,是org.slf4j.Logger的實現(xiàn)類范删。獲取Logger的過程可以分為
- 是否是root蕾域,如果是,返回root
- 從loggerCache緩存中獲取到旦,loggerCache中包含了配置文件中解析出來的logger信息和之前create過的logger
- 將logger name以"."分割旨巷,獲取或者創(chuàng)建的logger,例如com.mujin.lnamp添忘,會創(chuàng)建名為com采呐、com.mujin、com.mujin.lnamp的logger搁骑,并將其放入loggerCache然后返回com.mujin.lnamp斧吐。logger是root logger的child即logger.parent=ROOT
至此獲取Logger完成又固,logback的Logger實現(xiàn)類為ch.qos.logback.classic.Logger
集成log4j
slf4j集成log4j需要引入slf4j-api、slf4j-log4j12会通、log4j三個Jar包口予,slf4j-log4j12用來起橋接作用。
獲取Logger的過程和logback的過程一樣涕侈,唯一不同的是StaticLoggerBinder的實現(xiàn)方式不一樣沪停,StaticLoggerBinder的構(gòu)造方法如下
private StaticLoggerBinder() {
loggerFactory = new Log4jLoggerFactory();
try {
Level level = Level.TRACE;
} catch (NoSuchFieldError nsfe) {
Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
}
}
只是新建了Log4jLoggerFactory的實例,Log4jLoggerFactory是ILoggerFactory的實現(xiàn)類裳涛。
log4j版的StaticLoggerBinder獲取logger過程如下
public Logger getLogger(String name) {
Logger slf4jLogger = loggerMap.get(name);
if (slf4jLogger != null) {
return slf4jLogger;
} else {
org.apache.log4j.Logger log4jLogger;
if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
log4jLogger = LogManager.getRootLogger();
else
log4jLogger = LogManager.getLogger(name);
Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
return oldInstance == null ? newInstance : oldInstance;
}
}
思路很清晰
- 從loggerMap中嘗試取出
- 如果logger name名為root木张,返回root
- 使用LogManager.getLogger返回Log4j的Logger實現(xiàn),其類型為 org.apache.log4j.Logger log4jLogger
- 使用Log4jLoggerAdapter包裝 org.apache.log4j.Logger log4jLogger端三,使其適配org.slf4j.Logger接口
- 將Log4jLoggerAdapter嘗試放入loggerMap緩存
那這樣就有個疑問了舷礼,log4j的配置文件如何加載的呢?答案在LogManager的靜態(tài)塊中
static {
Hierarchy h = new Hierarchy(new RootLogger(Level.DEBUG));
repositorySelector = new DefaultRepositorySelector(h);
String override = OptionConverter.getSystemProperty("log4j.defaultInitOverride", (String)null);
if(override == null || "false".equalsIgnoreCase(override)) {
String configurationOptionStr = OptionConverter.getSystemProperty("log4j.configuration", (String)null);
String configuratorClassName = OptionConverter.getSystemProperty("log4j.configuratorClass", (String)null);
URL url = null;
if(configurationOptionStr == null) {
url = Loader.getResource("log4j.xml");
if(url == null) {
url = Loader.getResource("log4j.properties");
}
} else {
try {
url = new URL(configurationOptionStr);
} catch (MalformedURLException var5) {
url = Loader.getResource(configurationOptionStr);
}
}
if(url != null) {
LogLog.debug("Using URL [" + url + "] for automatic log4j configuration.");
OptionConverter.selectAndConfigure(url, configuratorClassName, getLoggerRepository());
} else {
LogLog.debug("Could not find resource: [" + configurationOptionStr + "].");
}
}
以上會去加載log4j.properties或log4j.xml等配置文件郊闯,然后進行初始化
總結(jié)
slf4j通過StaticLoggerBinder鏈接log4j/logback妻献,log4j/logback都提供了對應(yīng)的StaticLoggerBinder實現(xiàn),而對于org.slf4j.Logger接口团赁,log4j提供的默認實現(xiàn)是Log4jLoggerAdapter育拨,logback提供的實現(xiàn)是ch.qos.logback.classic.Logger。通過以上分析欢摄,我們可以回答兩個問題了
- 如何判斷系統(tǒng)中使用了slf4j日志門面熬丧?
- 可以通過Class.forName("org.slf4j.impl.StaticLoggerBinder"),如果沒有拋出ClassNotFoundException說明使用了slf4j
- 如何判斷系統(tǒng)使用了slf4j+log4j還是slf4j+logback
- 可以通過LogFactory.getLogger的返回類型判斷怀挠,log4j實現(xiàn)是Log4jLoggerAdapter析蝴,logback實現(xiàn)是ch.qos.logback.classic.Logger
基于以上手段,我們可以做出一套適配log4j或者logback的日志記錄工具類了绿淋,后續(xù)將有相關(guān)博文給出