Log4j.properties文件的加载

org.apache.log4j.LogManager类有一个静态块,首先是找 log4j.xml,找不到的情况下才找 log4j.properties
Java code
    
    
    
    
// 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)去找了,
Java code
    
    
    
    
// 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里去找,找不到才自己去找
Java code
    
    
    
    
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优先 你可以自己测试一下。



以上是个人意见,希望你结合自己的测试结果看看。

你可能感兴趣的:(tomcat,应用服务器,log4j,ClassLoader,null,url)