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.

咱们知道类的加载确定是类加载来选择的,那么类加载器究竟是如何选择的?首先咱们要理解类加载器的机制。类加载器

相关文章
相关标签/搜索