log4j配置文件log4j.properties的默认路径问题

来源:互联网 发布:免费虚拟机 for mac 编辑:程序博客网 时间:2024/05/17 02:47

在以前的项目里总是在Listener里配置(PropertyConfigurator.configure(“log.properties”)) log 的配置文件或者基于Spring的Log4jConfigListener加载,web.xml 设置。今天在一个项目中遇到一个问题,没有任何地方配置log4j的配置文件。只是在src目录下有log4j.properties 文件,log可以输出,但是不知道输出到哪里了,后来产看才知道在log4j.properties 发现用的是catalina.home{catalina.base}, 在${catalina.home}\logs 果然找到了日志文件。 但疑惑是log4j的配置文件是怎么加载进去的呢?

默认的配置文件log4j.properties,只要放到classpath中,就会被log实现自动加载,不需要做任何配置,log4j的实现jar会在第一次使用的时候会加载配置文件。

log4j 默认的是第一次调用是从classpath中查找log4j.xml 文件,找不到再找log4j.properties 文件,使用类加载器找到相应文件, 如果带/,是从classpath 根目录下搜索,否则从类Loader所在的路径下开始搜索,从源码可以看到只给了文件名,没有/, 所以从类文件所在路径开始搜。

这里写图片描述

org.apache.log4j.LogManager

static public final String DEFAULT_CONFIGURATION_FILE = “log4j.properties”;
static final String DEFAULT_XML_CONFIGURATION_FILE = “log4j.xml”;
static final public String DEFAULT_CONFIGURATION_KEY=”log4j.configuration”;
static {
URL url = null;
// 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);
}
}

使用类加载器找到相应文件, 如果带/,是从classpath 根目录下搜索,否则从类Loader所在的路径下开始搜索,
/*
org.apache.log4j.helpers.Loader.getResource(String resource)

This method will search for resource in different places. The search order is as follows:
Search for resource using the thread context class loader under Java2. If that fails, search for resource using the class loader that loaded this class (Loader). Under JDK 1.1, only the the class loader that loaded this class (Loader) is used.
Try one last time with ClassLoader.getSystemResource(resource), that is is using the system class loader in JDK 1.2 and virtual machine’s built-in class loader in JDK 1.1.
*/

static public URL getResource(String resource) {    ClassLoader classLoader = null;    URL url = null;       try {    if(!java1) {       classLoader = getTCL();       if(classLoader != null)              url = classLoader.getResource(resource);//           if(url != null)              return url;    }    classLoader = Loader.class.getClassLoader();    if(classLoader != null)          url = classLoader.getResource(resource);         if(url != null)             return url;    return ClassLoader.getSystemResource(resource);  }

REFER:
http://blog.csdn.net/caomiao2006/article/details/22062001
http://blog.csdn.net/caomiao2006/article/details/22079803
http://bbs.csdn.net/topics/120015149

0 0