log4j 加载顺序

来源:互联网 发布:suse linux yum配置 编辑:程序博客网 时间:2024/06/06 07:02
首先是:
org.apache.log4j.LogManager类有一个静态块,首先是找log4j.xml,找不到的情况下才找log4j.properties
Java code
?
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)去找了,
Java code
?
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里去找,找不到才自己去找
Java code
?
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优先 你可以自己测试一下。
0 0
原创粉丝点击