---
title: "Log4j 配置文件的位置"
author: "ahuango"
date: "2010-04-09T09:02:26Z"
tags: []
categories: ["编程语言"]
slug: "log4j"
draft: false
lastmod: "2010-04-09T09:07:23Z"
id: 638685
url: "https://ahuango.iteye.com/blog/638685"
---

如果log4j.properties/xml 不在ClassPath 下，则会出现如下的错误：

    log4j:WARN No appenders could be found for logger (xxxxx).
    log4j:WARN Please initialize the log4j system properly.

所以需要把配置文件放在类路径下。因为Log4j的LogManager类在静态初始化的时候，会从当前线程的类路径中找配置文件。

在eclipse中，我们常常会放在src目录下，这样就会编译到bin目录中，运行时就会被load到类路径中。

如果，我们不想把一个配置文件挂在src下，而是放在一个单独的conf目录下，那么我们可以通过写一个classloader来保证我们可以找到这个文件。具体目录：
![](http://dl.iteye.com/upload/attachment/231409/bb8d5bf6-0f0f-3c84-a66c-d9384b9ece34.bmp)
我们可以写一个URLClassLoader 并把它的URL 设置为指向Conf目录，它的parent为当前的应用程序ClassLoader，并把它设置为当前线程的ClassLoader。

```java

private static void initClassLoader() {
	try {
		File dir = new File(ServerProperties.getConfigUrl());
		URL url = dir.toURI().toURL();
		appLoader = new URLClassLoader(new URL[]{url},Startup.class.getClassLoader());
	} catch(MalformedURLException urle) {
		urle.printStackTrace();
	}
}
```


```java
Thread.currentThread().setContextClassLoader(appLoader);
```


这一切都必须在第一次声明一个Log对象之前完成。 Log的配置信息只在第一次使用LogManager的时候被设置。