在Tomcat 定制JNDI URL Resource中我介绍了如何在tomcat中实现URL资源访问,在Log4j配置实践中我介绍了在Web应用中如何使用log4j xml配置方式记录日志。这篇我要介绍如何在Web应用中把Log4j和JNDI结合起来,达到可以动态修改Log4j配置文件路径和Log4j日志文件存储路径的目的。
我们知道,Spring本身提供了Log4jConfigListener和Log4jWebConfigurer来帮助初始化Log4j,其中参数log4jConfigLocation可以在classpath或者按指定路径查找log4j配置文件,log4jRefreshInterval指定检查加载配置文件变化。在这里,我们要做的是根据Log4jConfigListener和Log4jWebConfiguer来定制自己的Log4jConfigListener,达到可以按JNDI来访问配置文件的目的。给出实现如下:
package com.demo;
/*...
import ...here
...
*/
public class JndiLog4jConfigListener implements ServletContextListener {
/** Parameter specifying the location of the log4j config file */
public static final String CONFIG_LOCATION_PARAM = "log4jConfigLocation";
/** Parameter specifying the location of the log4j config file */
public static final String CONFIG_FILENAME_PARAM = "log4jConfigFilename";
/** Parameter specifying the refresh interval for checking the log4j config file */
public static final String REFRESH_INTERVAL_PARAM = "log4jRefreshInterval";