Medusar's Blog
敬畏知识,谦逊前行
Toggle navigation
Medusar's Blog
主页
Booklist
Resources
About Me
归档
标签
Commons-logging启动原理
日志
框架
源码
2016-03-07 16:09:42
505
0
0
medusar
日志
框架
源码
## Commons-Logging的使用 ``` java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class App { private static final Log log = LogFactory.getLog(App.class); public static void main( String[] args ) { log.info("rizhi ...."); } } ``` ## 启动过程分析 可以看到,Log是通过LogFactory.getLog(Class clzz)方法获取的。 而getLog方法内部又是通过getFactory()方法,先获取到LogFactory,然后再创建Log的。 所以,commons-logging在选在使用哪个日志实现的时候,实际上是先选择使用哪个LogFactory。下面我们就来看一下这个过程(LogFactory类的public static LogFactory getFactory() throws LogConfigurationException方法)。 ### 1. 首先查找缓存的LogFactory,找到就直接返回,否则继续下一步 ``` java // 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; } ``` ### 2. 尝试从名为`LogFactory`的系统变量中获取LogFactory的实现类类名,如果找到则创建该工厂并返回,否则下一步。 ``` java 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; } ``` ### 3. 如果第二步创建失败,则通过使用JDK1.3的类发现机制,尝试从META-INF/services目录下org.apache.commons.logging.LogFactory文件中查找实现类(SPI),找到就创建,否则下一步。 ``` java // 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 } } ``` ### 4. 如果仍没成功,则从`commons-logging.properties`文件中读取实现类,并创建,否则下一步。 ``` java 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.."); } } } ``` 上面代码中的`prop`是在前面的代码中读取的,是一个Properties,如下 ``` java Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES); ``` ### 5. 如果上面仍没成功,则使用默认的`org.apache.commons.logging.impl.LogFactoryImpl`类,作为LogFactory实现类。 ``` java // 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); } ``` ### 注意: 上面的代码中有好打印诊断信息的方法,例如: ``` java 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)."); } ``` 该方法打印有助于帮助我们理解该过程,我们可以设置开启该功能,将我们的代码改成下面的形式: ``` java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class App { static { System.setProperty("org.apache.commons.logging.diagnostics.dest","STDOUT"); } private static final Log log = LogFactory.getLog(App.class); public static void main( String[] args ) { System.out.println("Hello World!"); log.info("asdfasdfasdf"); } } ``` 运行日志如下: ``` bash [LogFactory ] [LOOKUP] LogFactory implementation requested for the first time for context classloader sun.misc.Launcher$AppClassLoader@589431969 [LogFactory ] [LOOKUP] sun.misc.Launcher$AppClassLoader@589431969 == 'sun.misc.Launcher$AppClassLoader@232204a1' [LogFactory ] [LOOKUP] ClassLoader tree:sun.misc.Launcher$AppClassLoader@589431969 (SYSTEM) --> sun.misc.Launcher$ExtClassLoader@1265094477 --> BOOT [LogFactory ] [LOOKUP] No properties file of name 'commons-logging.properties' found. [LogFactory ] [LOOKUP] Looking for system property [org.apache.commons.logging.LogFactory] to define the LogFactory subclass to use... [LogFactory ] [LOOKUP] No system property [org.apache.commons.logging.LogFactory] defined. [LogFactory ] [LOOKUP] Looking for a resource file of name [META-INF/services/org.apache.commons.logging.LogFactory] to define the LogFactory subclass to use... [LogFactory ] [LOOKUP] No resource file with name 'META-INF/services/org.apache.commons.logging.LogFactory' found. [LogFactory ] [LOOKUP] No properties file available to determine LogFactory subclass from.. [LogFactory ] [LOOKUP] Loading the default LogFactory implementation 'org.apache.commons.logging.impl.LogFactoryImpl' via the same classloader that loaded this LogFactory class (ie not looking in the context classloader). ``` 经过上面的步骤,LogFactory的实现类就找到了。接下来就是要创建Log。 ## 创建Log的过程 创建Log我们可以通过查看commons-logging的默认LogFactory实现:`org.apache.commons.logging.impl.LogFactoryImpl`。 关键的方法是:`discoverLogImplementation` 它会首先查找用户指定的Log实现类: ``` java // See if the user specified the Log implementation to use String specifiedLogClassName = findUserSpecifiedLogClassName(); if (specifiedLogClassName != null) { if (isDiagnosticsEnabled()) { logDiagnostic("Attempting to load user-specified log class '" + specifiedLogClassName + "'..."); } result = createLogFromClass(specifiedLogClassName, logCategory, true); if (result == null) { StringBuffer messageBuffer = new StringBuffer("User-specified log class '"); messageBuffer.append(specifiedLogClassName); messageBuffer.append("' cannot be found or is not useable."); // Mistyping or misspelling names is a common fault. // Construct a good error message, if we can informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LOG4J_LOGGER); informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_JDK14_LOGGER); informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LUMBERJACK_LOGGER); informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_SIMPLE_LOGGER); throw new LogConfigurationException(messageBuffer.toString()); } return result; } ``` 如果用户没有指定,则按照如下顺序查找: 1. org.apache.commons.logging.impl.Log4JLogger 2. org.apache.commons.logging.impl.Jdk14Logger 3. org.apache.commons.logging.impl.Jdk13LumberjackLogger 4. org.apache.commons.logging.impl.SimpleLog 即会首先查找Log4j的实现,然后是JDK的,如果都没有找到,则用commons-logging自己的。 ``` java for(int i=0; i<classesToDiscover.length && result == null; ++i) { result = createLogFromClass(classesToDiscover[i], logCategory, true); } ``` 通过commons-logging的诊断日志信息也可以看出来: 日志信息如下: ``` bash [LogFactoryImpl@723074861] Trying to get log class from attribute 'org.apache.commons.logging.Log' [LogFactoryImpl@723074861] Trying to get log class from attribute 'org.apache.commons.logging.log' [LogFactoryImpl@723074861] Trying to get log class from system property 'org.apache.commons.logging.Log' [LogFactoryImpl@723074861] Trying to get log class from system property 'org.apache.commons.logging.log' [LogFactoryImpl@723074861] No user-specified Log implementation; performing discovery using the standard supported logging implementations... [LogFactoryImpl@723074861] Attempting to instantiate 'org.apache.commons.logging.impl.Log4JLogger' [LogFactoryImpl@723074861] Trying to load 'org.apache.commons.logging.impl.Log4JLogger' from classloader sun.misc.Launcher$AppClassLoader@589431969 [LogFactoryImpl@723074861] Class 'org.apache.commons.logging.impl.Log4JLogger' was found at 'jar:file:/D:/m2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar!/org/apache/commons/logging/impl/Log4JLogger.class' [LogFactoryImpl@723074861] The log adapter 'org.apache.commons.logging.impl.Log4JLogger' is missing dependencies when loaded via classloader sun.misc.Launcher$AppClassLoader@589431969: org/apache/log4j/Priority [LogFactoryImpl@723074861] Attempting to instantiate 'org.apache.commons.logging.impl.Jdk14Logger' [LogFactoryImpl@723074861] Trying to load 'org.apache.commons.logging.impl.Jdk14Logger' from classloader sun.misc.Launcher$AppClassLoader@589431969 [LogFactoryImpl@723074861] Class 'org.apache.commons.logging.impl.Jdk14Logger' was found at 'jar:file:/D:/m2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar!/org/apache/commons/logging/impl/Jdk14Logger.class' ``` ## 总结 commons-logging通过LogFactory来创建Log,所以,开发者可以选择自己实现一个LogFactory,从而控制Log实例的创建过程,比如Log4j的`SLF4JLogFactory`。如果开发者不想实现,可以使用commons-logging提供的默认LogFactory实现,然后根据它自己实现的规则,指定自己需要的Log实例。自己实现LogFactory的方式,控制度更高,也更复杂。
上一篇:
Redis集群学习
下一篇:
Linux中设置Java环境变量
0
赞
505 人读过
新浪微博
微信
腾讯微博
QQ空间
人人网
Please enable JavaScript to view the
comments powered by Disqus.
comments powered by
Disqus
文档导航