方法一:使用spring提供的配置
此方法在spring4.x的版本中都可以使用,但在Spring 4.2.1中已经将其标记为过时了.如果使用spring4.2.1以上的版本又会造成不兼容
Log4jConfigListener必须要在Spring的Listener之前。
web.xml
<!-- 设置由Sprng载入的Log4j配置文件位置 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>10000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
方法二:
使用log4j提供的方法自定义类并引入到spring中.
<!--配置log4j自动加载日志--> <bean class="com.upcloud.web.util.Log4jConfig"> <constructor-arg name="reload" value="true"/> <constructor-arg name="interval" value="60000"/> </bean>
代码如下:
package com.upcloud.web.util; import org.apache.log4j.PropertyConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Log4jConfig { private boolean reload = true; private int interval = 60000; private static final Logger logger = LoggerFactory.getLogger(Log4jConfig.class); /** * log4j日志自动加载 * * @param reload 是否开启自动加载 * @param interval 自动加载时间(ms) */ public Log4jConfig(boolean reload, int interval) { this.reload = reload; this.interval = interval; this.loadConfig(); } public void loadConfig() { String log4jPath = Log4jConfig.class.getClassLoader().getResource("log4j.properties").getPath(); logger.debug("log4j file path: " + log4jPath); // 间隔特定时间,检测文件是否修改,自动重新读取配置 PropertyConfigurator.configureAndWatch(log4jPath, this.interval); } }