应用场景与问题
当项目在运行时,我们如果需要修改log4j 1.X或者log4j2的配置文件,一般来说我们是不能直接将项目停止运行再来修改文件重新部署的。于是就有这样一个问题:如何在不停止当前项目的运行的情况下,让系统能够自动地监控配置文件的修改状况,从而实现动态加载配置文件的功能?而log4j 1.X和log4j2的差别略大,各自应该怎么实现这个功能?
log4j 1.X动态加载配置文件
log4j 1.X提供了动态加载配置文件的方法:
DOMConfigurator.configureAndWatch()
PropertyConfigurator.onfigureAndWatch()
DOMConfigurator对应的是xml配置文件,PropertyConfigurator对应的是properties配置文件。这两个类都有configureAndWatch这个方法,该方法有个重载方法,如下:
configureAndWatch(String configFilename)
configureAndWatch(String configFilename, long delay)
configureAndWatch方法用来监控配置文件是否被改动,监控的时间间隔是delay参数来决定,如果不传入该参数则使用默认的时间间隔1分钟(60000L)。configureAndWatch(String configFilename)实际上还是调用的configureAndWatch(String configFilename, long delay)。
代码示例:
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;
import org.apache.log4j.PropertyConfigurator;
try {
String resolvedLocation = SystemPropertyUtils.resolvePlaceholders("classpath:log4j.properties");
File file = ResourceUtils.getFile(resolvedLocation);
if (file.exists()) {
PropertyConfigurator.configureAndWatch(file.getAbsolutePath(), TimeUnit.SECONDS.toMillis(5));
} else {
LOGGER.error("classpath:log4j.properties");
}
} catch (Exception e) {
LOGGER.error("开启log4j日志监控报错了", e);
}
log4j2动态加载配置文件
和log4j 1.X比起来,log4j2的动态加载配置很简单就能实现,不需要另外在代码中调用api,方法如下:
<configuration monitorInterval="30">
...
</configuration>
在log4j2.xml配置文件中的configuration节点添加monitorInterval的值,单位是秒,如果配置的值大于0,则会按照时间间隔来自动扫描配置文件是否被修改,并在修改后重新加载最新的配置文件。如果不配置该值,默认为0,即不扫描配置文件是否被修改。
参考文章
动态加载配置文件的底层实现原理watchDog
https://www.cnblogs.com/yulinlewis/p/10177196.html