在项目中使用到文件变化的监控,在Log4j中同样也有文件监控功能具体实现类为FileWatchdog。当系统启动的时候,加载log4j的时候,记录log4j配置文件最后修改时间,每间隔一段时间,获取log4j的配置文件的最后修改时间如果大于内存中记录最后修改时间,说明log4j配置文件改变。则重新加载log4j配置文件。
log4j变化监控类:
package com.easyway.app.log4j.file; import java.io.File; import org.apache.log4j.helpers.LogLog; /** *log4j源代码分析,在Log4j中同样也有文件监控功能具体实现类为FileWatchdog。 *当系统启动的时候,加载log4j的时候,记录log4j配置文件最后修改时间,每间隔一段时间, *获取log4j的配置文件的最后修改时间如果大于内存中记录最后修改时间,说明log4j配置文件改变。 *则重新加载log4j配置文件。 * @author longgangbai * */ public abstract class FileWatchdog extends Thread { protected FileWatchdog(String filename) { super("FileWatchdog"); delay = 60000L; lastModif = 0L; warnedAlready = false; interrupted = false; this.filename = filename; file = new File(filename); //设置为后台进程 setDaemon(true); //启动开始检查 checkAndConfigure(); } public void setDelay(long delay) { this.delay = delay; } /** * 重新加载log4j配置文件 * */ protected abstract void doOnChange(); /** * 检查log4j配置文件变化的方法 * */ protected void checkAndConfigure() { boolean fileExists; //检查文件是否存在, try { fileExists = file.exists(); } catch (SecurityException e) { LogLog.warn("Was not allowed to read check file existance, file:[" + filename + "]."); interrupted = true; return; } //如果存在获取最后修改时间与内存记录的原最后修改时间比较 if (fileExists) { long l = file.lastModified(); if (l > lastModif) { lastModif = l; doOnChange(); warnedAlready = false; } } else if (!warnedAlready) { LogLog.debug("[" + filename + "] does not exist."); warnedAlready = true; } } /** * 执行执行的方法 */ public void run() { while (!interrupted) { try { //检查的修改时间间隔 Thread.sleep(delay); } catch (InterruptedException e) { } //检查log4j配置 checkAndConfigure(); } } public static final long DEFAULT_DELAY = 60000L; protected String filename; protected long delay; File file; long lastModif; boolean warnedAlready; boolean interrupted; }
log4j.xml配置文件监控类:
package com.easyway.app.log4j.file; import org.apache.log4j.LogManager; import org.apache.log4j.helpers.FileWatchdog; import org.apache.log4j.xml.DOMConfigurator; /** * 针对log4j.xml变化加载的方法 * @author longgangbia * */ public class XMLWatchdog extends FileWatchdog { public XMLWatchdog(String filename) { super(filename); } public void doOnChange() { (new DOMConfigurator()).doConfigure(super.filename, LogManager .getLoggerRepository()); } }
针对log4j.properties文件监控实现类:
package com.easyway.app.log4j.file; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.FileWatchdog; /** * 针对log4j.properties变化加载的方法 * @author longgangbia * */ class PropertyWatchdog extends FileWatchdog { PropertyWatchdog(String filename) { super(filename); } public void doOnChange() { (new PropertyConfigurator()).doConfigure(super.filename, LogManager .getLoggerRepository()); } }