1. slf4j简介
slf4j不是一个具体的日志解决方案,它只是服务于各种各样的日志系统。就像JDBC一样,它只是作为一个用于日志系统的Facade,但它比JDBC更简单,JDBC需要你去指定驱动,而slf4j只需你将具体的日志系统的jar包添加到classpath即可。
slf4j提供了一些重要的API定义及LoggerFactory类。但LoggerFactory不是可以具体创建Logger对象的工厂,它的主要功能是绑定你所指定的Factory,并使用绑定的LoggerFactory来创建你所需要的Logger对象。
2. 源码分析
我们在记录日志的时候要获得一个Logger对象,代码如下
那么我们知道LoggerFactory是依赖于你指定的具体的日志系统来创建Logger,那么它是如何找到指定的LoggerFactory?
首先看 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();
}
}
绑定具体的LoggerFactory
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;
}
下面看最重要的一行代码
StaticLoggerBinder.getSingleton();
首先我们要明白StaticLoggerBinder是干什么的。每一个要与slf4j对接的具体实现的日志系统,都要实现一个包名为org.slf4j.impl且类名为StaticLoggerBinder的类,该类实现了LoggerFactoryBinder接口。
logback的实现
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.
我们知道类的加载肯定是类加载来选择的,那么类加载器到底是如何选择的?首先我们要理解类加载器的机制。类加载器