文
章
目
录
章
目
录
在项目运行时,若需修改log4j 1.X或log4j2的配置文件,通常不能直接停止项目然后修改并重新部署。因此,面临的问题是在不停止项目的情况下,如何实现系统自动监控配置文件的修改并动态加载?log4j 1.X和log4j2的机制有所不同,各自应如何实现此功能?
log4j 1.X 动态加载配置文件
log4j 1.X提供了动态加载配置文件的方法:
// DOMConfigurator对应的是xml配置文件
DOMConfigurator.configureAndWatch()
//PropertyConfigurator对应的是properties配置文件
PropertyConfigurator.onfigureAndWatch()
这两个类都有configureAndWatch
这个方法,该方法有个重载方法,如下:
configureAndWatch(String configFilename)
configureAndWatch(String configFilename, long delay)
configureAndWatch
方法用来监控配置文件是否被改动,监控的时间间隔是delay
参数来决定,如果不传入该参数则使用默认的时间间隔1分钟(60000L)。configureAndWatch(String configFilename)
本质上上还是调用的configureAndWatch(String configFilename, long delay)
。
log4j2 动态加载配置文件
和log4j 1.X比起来,log4j2的动态加载配置很简单就能实现,不需要另外在代码中调用api,配置如下(90秒扫描一次):
<configuration monitorInterval="90">
...
</configuration>
在log4j2.xml配置文件中的configuration
节点添加monitorInterval
的值,单位是秒,如果配置的值大于0,则会按照时间间隔来自动扫描配置文件是否被修改,并在修改后重新加载最新的配置文件。如果不配置该值,默认为0,即不扫描配置文件是否被修改。