l​o​g​4​j​.​p​r​o​p​e​r​t​i​e​s​文​件​放​置​在​其​它​目​录​下

一般我们直接将log4j.properties放置在src目录下,这样系统自动会找到的,其实就是放在WEB-INF/classes文件下。这个路径在classpath下,所以直接就能找到。我们写Logger的时候如下:

 

public class HelloLog4j {

 

    public static Logger logger = Logger.getLogger(HelloLog4j.class);

 

    public static void main(String[] args) {       

        logger.debug("This is debug message.");

        logger.info("This is info message.");

        logger.error("This is error message.");

        xxx();

    }

   

    public static void xxx(){

        logger.debug("main method has invoked xxx method.");

    }

}

 

如果现在我们想把log4j.properties文件放置在其它目录下,例如:WEB-INF下和web.xml放在一起。这时候就需要我们手动指定log4j配置文件的路径,否则系统是找不到的。

 

一、首先我们在web.xml中配置好log4j.properties路径:

 

        <context-param>

            <param-name>log4jConfigLocation</param-name>

            <param-value>/WEB-INF/log4j.properties</param-value>

        </context-param>

 

二、然后写个servlet,部分代码如下:

 

public void init() {

    String prefix = getServletContext().getRealPath("/");

    String file = getInitParameter("log4jConfigLocation");

    if (file != null) {

      PropertyConfigurator.configure(prefix + file);    

    }

}

 

三、在web.xml中配置servlet,并将log4jConfigLocation加入到Servlet中,让其Server启动即运行:

 

<servlet>

   <servlet-name>your servlet</servlet-name>

   <servlet-class>your servelt class</servlet-class>

   <init-param>

      <param-name>log4jConfigLocation</param-name>

      <param-value>/WEB-INF/log4j.properties</param-value>

    </init-param>

   <load-on-startup>1</load-on-startup>

</servlet>

但是,如果放在SSH中时,servlet被封装了,还要这样写吗??当然不需要。但如果位置发生变化了,该如何处理呢?

<!-- ① 指定 Log4J 配置文件的地址 -->

<context-param>

<param-name>log4jConfigLocation</param-name>

<param-value>\WEB-INF\classes\coo\log4j.properties</param-value>

</context-param>

 

<!-- ② 使用该监听器初始化 Log4J 日志引擎  -->

<listener>

<listener-class>org.springframework.web.util.Log4jConfigListener </listener-class>

</listener>

 

<!-- Introspector 缓存清除监听器  -->

<listener>

<listener-class>org.springframework.web.util.IntrospectorCleanupListener </listener-class>

</listener>

注:在配置中“/”与"\"最终都被编译成“\”

posted @ 2014-07-16 20:59  大大的海棠湾  阅读(99)  评论(0)    收藏  举报