slf4j源碼分析

1. slf4j簡介

  • slf4j不是一個具體的日誌解決方案,它只是服務於各類各樣的日誌系統。就像JDBC同樣,它只是做爲一個用於日誌系統的Facade,但它比JDBC更簡單,JDBC須要你去指定驅動,而slf4j只需你將具體的日誌系統的jar包添加到classpath便可。html

  • slf4j提供了一些重要的API定義及LoggerFactory類。但LoggerFactory不是能夠具體建立Logger對象的工廠,它的主要功能是綁定你所指定的Factory,並使用綁定的LoggerFactory來建立你所須要的Logger對象。java

2. 源碼分析

咱們在記錄日誌的時候要得到一個Logger對象,代碼以下apache

那麼咱們知道LoggerFactory是依賴於你指定的具體的日誌系統來建立Logger,那麼它是如何找到指定的LoggerFactory?api

首先看 LoggerFactory.getLogger(Class<?> clazz)源碼分析

public static Logger getLogger(Class<?> clazz) {
    Logger logger = getLogger(clazz.getName());
    if (DETECT_LOGGER_NAME_MISMATCH) {
        Class<?> autoComputedCallingClass = Util.getCallingClass();
        if (nonMatchingClasses(clazz, autoComputedCallingClass)) {
            Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".",
                    logger.getName(), autoComputedCallingClass.getName()));
            Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");
        }
    }
    return logger;
}
public static Logger getLogger(String name) {
	// 獲取具體的LoggerFactory
    ILoggerFactory iLoggerFactory = getILoggerFactory();
    return iLoggerFactory.getLogger(name);
}
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;
 
public static ILoggerFactory getILoggerFactory() {
	// 若是沒有進行初始化(未綁定具體的LoggerFactory),就進行初始化,初始狀態就是UNINITIALIZED,因此第一次執行時進入performInitialization()方法
    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() {
	// 綁定具體的LoggerFactory
    bind();
    if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
		// 查看是否知足特定的jdk版本
        versionSanityCheck();
    }
}

綁定具體的LoggerFactoryui

private final static void bind() {
    try {
		// 找到classpath下全部的StaticLoggerBinder
        Set<URL> staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
 
		// 若是StaticLoggerBinder多於1個則報告異常
        reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
		
        // 此處是重點,詳細解釋看下面
        StaticLoggerBinder.getSingleton();
 
		// 將初始化狀態置爲成功
        INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
        reportActualBinding(staticLoggerBinderPathSet);
        fixSubstitutedLoggers();
    } 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);
    }
}
// We need to use the name of the StaticLoggerBinder class, but we can't reference
// the class itself.
private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"
 
private static Set<URL> findPossibleStaticLoggerBinderPathSet() {
    
    Set<URL> staticLoggerBinderPathSet = new LinkedHashSet<URL>();
    try {
		// 拿到當前類的類加載器
        ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
        Enumeration<URL> paths;
        if (loggerFactoryClassLoader == null) {
            paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
        } else {
			// 類加載器找到classpath下全部的"org/slf4j/impl/StaticLoggerBinder.class"類的絕對路徑
			// 例如 "file:/Users/lushun/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.1/log4j-slf4j-impl-2.1.jar!/org/slf4j/impl/StaticLoggerBinder.class"
            paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH);
        }
        while (paths.hasMoreElements()) {
            URL path = (URL) paths.nextElement();
            staticLoggerBinderPathSet.add(path);
        }
    } catch (IOException ioe) {
        Util.report("Error getting resources from path", ioe);
    }
    return staticLoggerBinderPathSet;
}

下面看最重要的一行代碼this

StaticLoggerBinder.getSingleton();

首先咱們要明白StaticLoggerBinder是幹什麼的。每個要與slf4j對接的具體實現的日誌系統,都要實現一個包名爲org.slf4j.impl且類名爲StaticLoggerBinder的類,該類實現了LoggerFactoryBinder接口。spa

logback的實現.net

log4j的實現日誌

且每一個類都實現了一個getSingleton()方法,來建立一個惟一的StatisLoggerBinder。

那麼StaticLoggerBinder.getSingleton()到底作了什麼事情。

  • 將StaticLoggerBinder加載到JVM中並建立一個StaticLoggerBinder的對象,此時就實現了綁定。

3. 總結及問題

3.1 總結

3.2 問題

剛纔的流程是分析在classpath中只有一個StaticLoggerBinder的狀況,那麼若是是兩個及兩個以上呢,即咱們將兩個或兩個以上的具體實現的日誌系統加入到classpath,那麼此時會有什麼問題。

例如咱們將logback log4j兩個都加入到classpath中。bind()執行時會有不一樣的表現

private final static void bind() {
    try {
		// 會找到兩個URL
        Set<URL> staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
 
		// 若是StaticLoggerBinder多於1個則報告異常
        reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
		
        StaticLoggerBinder.getSingleton();
 
		// 將初始化狀態置爲成功
        INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
        reportActualBinding(staticLoggerBinderPathSet);
        fixSubstitutedLoggers();
    } catch (NoClassDefFoundError ncde) {
		// do something
    }
}

reportMultipleBindingAmbiguity(staticLoggerBinderPathSet)會報告異常,output以下

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:ch/qos/logback/logback-classic/1.0.0/logback-classic-1.0.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:org/apache/logging/log4j/log4j-slf4j-impl/2.1/log4j-slf4j-impl-2.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.

StaticLoggerBinder.getSingleton()會加載哪一個StaticLoggerBinder?reportActualBinding(staticLoggerBinderPathSet)輸出結果?

private static void reportActualBinding(Set<URL> staticLoggerBinderPathSet) {
    if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) {
        Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]");
 	}
}

在本次試驗中output:SLF4J: Actual binding is of type [ch.qos.logback.classic.selector.DefaultContextSelector],說明綁定的是logback的StaticLoggerBinder.

咱們知道類的加載確定是類加載來選擇的,那麼類加載器究竟是如何選擇的?首先咱們要理解類加載器的機制。類加載器

相關文章
相關標籤/搜索