---
title: "log4j.properties的路径问题"
author: "esperanza"
date: "2011-06-20T11:59:19Z"
tags: []
categories: ["编程语言"]
slug: "log4j-properties"
draft: false
lastmod: "2011-06-20T12:19:45Z"
id: 1098371
url: "https://0411.iteye.com/blog/1098371"
---

log4j.properties如果放在web-inif/classes目录下，会被自动加载。而且很多的开源框架，比如struts2也会默认从这个文件目录下读取log4j的配置文件。

如果框架用多了，那么这些配置文件就不大好管理，我想单独建一个config文件夹，用来存放配置文件

问题就出现了，一直抛异常：log4j:ERROR Could not read configuration file。代码如下：

PropertyConfigurator.configure(Log4jConfig.class.getClassLoader().getResource("") + "config/log4j.properties")

从console打印出来的日志来看，文件指定的路径非常的正确就是project/web-inf/classes/config/log4j.properties

 

但是，如果我使用下面的代码就没有问题了，但是有点别扭，因为有IOException要tyr-catch

Properties p = new Properties();  
p.load(Log4jConfig.class.getResourceAsStream("/config/log4j.properties"));  
PropertyConfigurator.configure(p);

 

无解...

 

  &lt;servlet&gt;  
    &lt;servlet-name&gt;Log4jServlet&lt;/servlet-name&gt;  
    &lt;servlet-class&gt;com.stock.finance.servlet.Log4jServlet&lt;/servlet-class&gt;  
    &lt;init-param&gt;  
      &lt;param-name&gt;config-file&lt;/param-name&gt;  
      &lt;param-value&gt;/WEB-INF/classes/config/log4j.properties&lt;/param-value&gt;  
    &lt;/init-param&gt;  
    &lt;load-on-startup&gt;10&lt;/load-on-startup&gt;  
  &lt;/servlet&gt; 

 

  String logFilePath = config.getInitParameter("config-file");  
  PropertyConfigurator.configure(getServletContext().getRealPath("") + logFilePath); 

 

  这样也能读取