项目用的是springmvc+spring+mybatis框架,

配置日志的时候非常简单,仅仅是把commons-logging、log4j,还有slf4j-log4j三个日志相关的jar包导入项目,然后在classpath中加个log4j.properties的配置文件即可。

但是你有没有想过Log4j是什么时候被加载进虚拟机的?为什么我们没有手动加载,spring和mybatis就能自动的用起来log4j,毫不见外?

spring使用的是commons-logging

mybatis用的是自己写的

看一下源码,非常简单,一个个的去试,没有这个就进入下一个,直到找到了log4j

这两个工具其实都只是日志工具的规范,可以理解成接口,而log4j才是一个实实在在的日志实现。

但是slf4j在什么地方?——虽然这两个工具没用到slf4j,我还是把它放进来,因为我引入的其他工具会用到它。。比如:

下面开始看代码代码来说明一下log4j是怎么被加载到虚拟机的:

首先我们来看spring,我们从web.xml看起,加载spring:

到这里我们看到了LogFactory,这是commons-logging的一个log工厂,这里用的是这个虚类的一个静态方法,我们继续看这个方法:

再看getFactory(代码较长,可以直接跳过先看后边的结论):

 public static LogFactory getFactory() throws LogConfigurationException {
// Identify the class loader we will be using
ClassLoader contextClassLoader = getContextClassLoaderInternal(); if (contextClassLoader == null) {
// This is an odd enough situation to report about. This
// output will be a nuisance on JDK1.1, as the system
// classloader is null in that environment.
if (isDiagnosticsEnabled()) {
logDiagnostic("Context classloader is null.");
}
} // Return any previously registered factory for this class loader
LogFactory factory = getCachedFactory(contextClassLoader);
if (factory != null) {
return factory;
} if (isDiagnosticsEnabled()) {
logDiagnostic(
"[LOOKUP] LogFactory implementation requested for the first time for context classloader " +
objectId(contextClassLoader));
logHierarchy("[LOOKUP] ", contextClassLoader);
} // Load properties file.
//
// If the properties file exists, then its contents are used as
// "attributes" on the LogFactory implementation class. One particular
// property may also control which LogFactory concrete subclass is
// used, but only if other discovery mechanisms fail..
//
// As the properties file (if it exists) will be used one way or
// another in the end we may as well look for it first. Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES); // Determine whether we will be using the thread context class loader to
// load logging classes or not by checking the loaded properties file (if any).
ClassLoader baseClassLoader = contextClassLoader;
if (props != null) {
String useTCCLStr = props.getProperty(TCCL_KEY);
if (useTCCLStr != null) {
// The Boolean.valueOf(useTCCLStr).booleanValue() formulation
// is required for Java 1.2 compatibility.
if (Boolean.valueOf(useTCCLStr).booleanValue() == false) {
// Don't use current context classloader when locating any
// LogFactory or Log classes, just use the class that loaded
// this abstract class. When this class is deployed in a shared
// classpath of a container, it means webapps cannot deploy their
// own logging implementations. It also means that it is up to the
// implementation whether to load library-specific config files
// from the TCCL or not.
baseClassLoader = thisClassLoader;
}
}
} // Determine which concrete LogFactory subclass to use.
// First, try a global system property
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] Looking for system property [" + FACTORY_PROPERTY +
"] to define the LogFactory subclass to use...");
} try {
String factoryClass = getSystemProperty(FACTORY_PROPERTY, null);
if (factoryClass != null) {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] Creating an instance of LogFactory class '" + factoryClass +
"' as specified by system property " + FACTORY_PROPERTY);
}
factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
} else {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] No system property [" + FACTORY_PROPERTY + "] defined.");
}
}
} catch (SecurityException e) {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] A security exception occurred while trying to create an" +
" instance of the custom factory class" + ": [" + trim(e.getMessage()) +
"]. Trying alternative implementations...");
}
// ignore
} catch (RuntimeException e) {
// This is not consistent with the behaviour when a bad LogFactory class is
// specified in a services file.
//
// One possible exception that can occur here is a ClassCastException when
// the specified class wasn't castable to this LogFactory type.
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] An exception occurred while trying to create an" +
" instance of the custom factory class" + ": [" +
trim(e.getMessage()) +
"] as specified by a system property.");
}
throw e;
} // Second, try to find a service by using the JDK1.3 class
// discovery mechanism, which involves putting a file with the name
// of an interface class in the META-INF/services directory, where the
// contents of the file is a single line specifying a concrete class
// that implements the desired interface. if (factory == null) {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] Looking for a resource file of name [" + SERVICE_ID +
"] to define the LogFactory subclass to use...");
}
try {
final InputStream is = getResourceAsStream(contextClassLoader, SERVICE_ID); if( is != null ) {
// This code is needed by EBCDIC and other strange systems.
// It's a fix for bugs reported in xerces
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
} String factoryClassName = rd.readLine();
rd.close(); if (factoryClassName != null && ! "".equals(factoryClassName)) {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] Creating an instance of LogFactory class " +
factoryClassName +
" as specified by file '" + SERVICE_ID +
"' which was present in the path of the context classloader.");
}
factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader );
}
} else {
// is == null
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] No resource file with name '" + SERVICE_ID + "' found.");
}
}
} catch (Exception ex) {
// note: if the specified LogFactory class wasn't compatible with LogFactory
// for some reason, a ClassCastException will be caught here, and attempts will
// continue to find a compatible class.
if (isDiagnosticsEnabled()) {
logDiagnostic(
"[LOOKUP] A security exception occurred while trying to create an" +
" instance of the custom factory class" +
": [" + trim(ex.getMessage()) +
"]. Trying alternative implementations...");
}
// ignore
}
} // Third try looking into the properties file read earlier (if found) if (factory == null) {
if (props != null) {
if (isDiagnosticsEnabled()) {
logDiagnostic(
"[LOOKUP] Looking in properties file for entry with key '" + FACTORY_PROPERTY +
"' to define the LogFactory subclass to use...");
}
String factoryClass = props.getProperty(FACTORY_PROPERTY);
if (factoryClass != null) {
if (isDiagnosticsEnabled()) {
logDiagnostic(
"[LOOKUP] Properties file specifies LogFactory subclass '" + factoryClass + "'");
}
factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); // TODO: think about whether we need to handle exceptions from newFactory
} else {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] Properties file has no entry specifying LogFactory subclass.");
}
}
} else {
if (isDiagnosticsEnabled()) {
logDiagnostic("[LOOKUP] No properties file available to determine" + " LogFactory subclass from..");
}
}
} // Fourth, try the fallback implementation class if (factory == null) {
if (isDiagnosticsEnabled()) {
logDiagnostic(
"[LOOKUP] Loading the default LogFactory implementation '" + FACTORY_DEFAULT +
"' via the same classloader that loaded this LogFactory" +
" class (ie not looking in the context classloader).");
} // Note: unlike the above code which can try to load custom LogFactory
// implementations via the TCCL, we don't try to load the default LogFactory
// implementation via the context classloader because:
// * that can cause problems (see comments in newFactory method)
// * no-one should be customising the code of the default class
// Yes, we do give up the ability for the child to ship a newer
// version of the LogFactoryImpl class and have it used dynamically
// by an old LogFactory class in the parent, but that isn't
// necessarily a good idea anyway.
factory = newFactory(FACTORY_DEFAULT, thisClassLoader, contextClassLoader);
} if (factory != null) {
/**
* Always cache using context class loader.
*/
cacheFactory(contextClassLoader, factory); if (props != null) {
Enumeration names = props.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = props.getProperty(name);
factory.setAttribute(name, value);
}
}
} return factory;
}

以上代码会先试图从classpath中加载commons-logging.properties等几个commons-logging才有的东西,直到208行代码,

我们看到最后创建了一个LogFactoryImpl的实例,然后返回了。

回头看看我们上边的代码:

看完了getFactory我们知道最后我们得到的是LogFactoryImpl的实例,

那么接下来我们该去这个类中看看它的getInstance方法了:

非常简单,在这里创建了一个Log的实例,这也是最关键的地方,我们去看看这个方法。

经过我个人进一步的代码分析logConstructor这个东西是空的,我就不再展开了,这时我们看541行这个方法,这里才是真正的创建Log实例:

这个方法名我们能看懂,就是去发现系统中的Log实现,也就是一个找的过程,后边的782行是找找系统变量中有没有commons-logging自己的指明实现类类名的变量,结果是没有的,因为我没有配。

这个方法还没完,中间是一大段的注释,我们直接看后边的重点:

这个时候开始遍历一个字符串数组,依此去系统中找有没有这个数组中的实现类,我们看看这个数组先。

大家看到了什么?log4j,现在大家基本已经知道为什么了,后边的代码如果还有兴趣可以自己去看,其实就是一个个的试着去系统中加载这些类,加载不到处理一下ClassNotFoundException然后继续找下一个。

完毕。

最后如果大家想看看commons-logging自己的日志,可以写一个Listener放在web xml第一个位置,把下边一句代码弄上:

你们会从日志中看到多了很多内容,其中有一句是:

[LogFactoryImpl@1302539661 from org.apache.catalina.loader.WebappClassLoader@1536551745] Class 'org.apache.commons.logging.impl.Log4JLogger' was found at 'jar:file:/E:/eaipweb/wtpwebapps/EAIP/WEB-INF/lib/commons-logging-1.1.1.jar!/org/apache/commons/logging/impl/Log4JLogger.class'

这回真完毕了。

最新文章

  1. Python ZIP压缩
  2. 循序渐进Python3(十二) --2--  web框架之django简单实现oracle数据库操作
  3. sql server 小记——分区表(上)
  4. [C#] 與Android共舞–手機post資料給Server (转帖)
  5. [vim]的关键字补全
  6. Rust入门篇 (1)
  7. 测试 __try, __finally, __except(被__finally捕获的异常, 还会被上一级的__except捕获。反之不行)
  8. 浅谈javascript中stopImmediatePropagation函数和stopPropagation函数的区别
  9. Android7.0 多窗口你值得拥有
  10. 【原】无脑操作:Centos 7后台运行及终止jar包程序
  11. Zabbix系列之八——安装agent监控windows
  12. 80端口被占用 导致apach无法启动问题
  13. jsp/servlet学习三之会话管理初解
  14. laravel的启动过程---摘自网络博客个人学习之用
  15. linux 实用指令
  16. mysql high availability 概述
  17. mysql的水平拆分和垂直拆分 (转)
  18. JavaScript JSON 数据处理
  19. kubectl error: The connection to the server localhost:8080 was refused
  20. Selenium - Css Selector 使用方法

热门文章

  1. 开发Android逆向工具
  2. BZOJ 4589 Hard Nim(FWT+博弈论+快速幂)
  3. [JSOI2018]军训列队
  4. [PKUSC2018]最大前缀和
  5. BUG:php7.1 访问yii数据库 自动加端口3306 报错
  6. mysql select 1
  7. 图解SQL Server:聚集索引、唯一索引、主键
  8. Oracle 11gR2 RAC 数据库不能连接(ORA-12537: TNS:connection closed)
  9. 【LaTeX】E喵的LaTeX新手入门教程(3)数学公式
  10. Ceph源码解析:Scrub故障检测