渊源
Logback 为log4j作者推出又一个日志框架,更好的实现了slf4j规范。
SLF4J 全称 Simple Logging Facade for Java。Facade 是一种设计模式,中文的一种翻译叫做 门面模式,可以类比为那句经典的,没有问题是加一层所不能解决的(大意,原话记不清了。。。。)。总结起来讲就是slf4j本身并没有提供日志记录的功能,仅仅是提供一个标准,具体的功能实现由具体的日志框架实现。详细的介绍见链接 https://www.slf4j.org/
环境设置
- 示例编辑环境使用idea
- 日志实现框架采用 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");
}
}
代码分析
//日志打印,日志功能实现,本次分析重点是初始化过程,并非具体日志打印功能实现
logger.info("slf4j");
//变量的初始化部分,本文关注的重点部分
private static final Logger logger = LoggerFactory.getLogger(Slf4jTest.class);
LoggerFactory.getLogger 方法一步步点进去(ctrl+alt+b,如果出现多个实现类的情况,则选择包名包含logback的进入)直到
/**
* 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);
}
发现出现一个Factory方法(getILoggerFactory),开始重点分析该方法实现,查看getILoggerFactory方法实现,代码如下:
/**
* 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 初始化的位置在哪?初始状态是什么?值是在哪里进行更新的?
- FAILED_INITIALIZATION , SUCCESSFUL_INITIALIZATION 等在哪里定义?都有哪些?含义是什么?
- performInitialization 方法执行了哪些操作?
- NOP_FALLBACK_FACTORY , TEMP_FACTORY 又是什么东西?
- StaticLoggerBinder.getSingleton().getLoggerFactory(); 这句代码做了什么见不得人的事情?
1.INITIALIZATION_STATE 初始化的位置在哪?初始状态是什么?值是在哪里进行更新的?
static int INITIALIZATION_STATE = UNINITIALIZED;
可以看出来 变量 INITIALIZATION_STATE 初始值为 UNINITIALIZED,字面含义是未被初始化状态。getILoggerFactory方法首先进行判断,如果 INITIALIZATION_STATE 值为 未初始化状体,先设置INITIALIZATION_STATE 状态为 初始化进行中状态(ONGOING_INITIALIZATION ),然后执行具体初始化操作,猜测在performInitialization()方法执行的过程中很有可能更新该值的操作。
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;
很明显这些类型的变量的创建是为了标识 工厂 初始化状态使用的,定义位置在LogFactory 类中,含义分别为(自上至下) 未被初始化,初始化进行中,初始化失败,初始化成功,NOP_FALLBACK_INITIALIZATION(no operation fallback initialization,这个不知道怎么翻译比较好)。
3.performInitialization 方法执行了哪些操作?
- 首先看performInitialization 方法实现
private final static void performInitialization() {
bind();
if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
versionSanityCheck();
}
}
- 追踪bind方法实现
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);
}
}
...未完待续
一天写一点,给自己加油>_<