本文主要是介绍log4j 加载顺序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先是:org.apache.log4j.LogManager类有一个静态块,首先是找 log4j.xml ,找不到的情况下才找 log4j.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // if the user has not specified the log4j.configuration // property, we search first for the file "log4j.xml" and then // "log4j.properties" if (configurationOptionStr == null ) { url = Loader.getResource(DEFAULT_XML_CONFIGURATION_FILE); if (url == null ) { url = Loader.getResource(DEFAULT_CONFIGURATION_FILE); } } else { try { url = new URL(configurationOptionStr); } catch (MalformedURLException ex) { // so, resource is not a URL: // attempt to get the resource from the class path url = Loader.getResource(configurationOptionStr); } } |
2,然后是怎么找呢:如下代码,是委托给classloader(加载Loader类的classloader)去找了,
1 2 3 4 5 6 7 8 9 10 11 | // We could not find resource. Ler us now try with the // classloader that loaded this class. classLoader = Loader. class .getClassLoader(); if (classLoader != null ) { LogLog.debug( "Trying to find [" +resource+ "] using " +classLoader + " class loader." ); url = classLoader.getResource(resource); if (url != null ) { return url; } } |
3,classloader的getResource(...)又是怎么找呢:总是先从父classloader里去找,找不到才自己去找
1 2 3 4 5 6 7 8 9 10 11 12 | public URL getResource(String name) { URL url; if (parent != null ) { url = parent.getResource(name); } else { url = getBootstrapResource(name); } if (url == null ) { url = findResource(name); } return url; } |
总结:对于不同的应用服务器(或者web服务器)来说,classloader的层次不尽相同。这里以最简单的tomcat来说,如果你的应用是部署到tomcat下的,使用log4j配置文件的顺序就是$TOMCAT_HOME/lib/log4j.xml或者log4j.properties==>你自己web应用/WEB-INF/classes(或者lib)/log4j.xml或者log4j.properties.
对于WEB-INF下是classes优先还是lib优先 你可以自己测试一下。
这篇关于log4j 加载顺序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!