要实现运行时切换日志策略,需要使用log4j中的
DOMConfigurator.configureAndWatch(location, refreshInterval) 或
PropertyConfigurator.configureAndWatch(location, refreshInterval)
location就是log4j配置文件的位置定位,refreshInterval是一个long型值,表示多少毫秒后重新加载配置文件。
spring通过org.springframework.util.Log4jConfigurer实现运行时切换需求,Log4jConfigurer正是对上述方法进行了封装。默认情况是1分钟重新加载一次。
log4j对配置文件变化的监视类是: org.apache.log4j.helpers.FileWatchdog
DOMConfigurator.configureAndWatch(location, refreshInterval) 或
PropertyConfigurator.configureAndWatch(location, refreshInterval)
location就是log4j配置文件的位置定位,refreshInterval是一个long型值,表示多少毫秒后重新加载配置文件。
spring通过org.springframework.util.Log4jConfigurer实现运行时切换需求,Log4jConfigurer正是对上述方法进行了封装。默认情况是1分钟重新加载一次。
log4j对配置文件变化的监视类是: org.apache.log4j.helpers.FileWatchdog
package org.apache.log4j.helpers;
import java.io.File;
import org.apache.log4j.helpers.LogLog;
public abstract class FileWatchdog extends Thread {
public static final long DEFAULT_DELAY = 60000;
protected String filename;
protected long delay = DEFAULT_DELAY;
File file;
long lastModif = 0;
boolean warnedAlready = false;
boolean interrupted = false;
protected FileWatchdog(String filename) {
this.filename = filename;
file = new File(filename);
setDaemon(true);
checkAndConfigure();
}
public void setDelay(long delay) {
this.delay = delay;
}
abstract protected void doOnChange();
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; // there is no point in continuing
return;
}
if(fileExists) {
long l = file.lastModified(); // this can also throw a SecurityException
if(l > lastModif) { // however, if we reached this point this
lastModif = l; // is very unlikely.
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) {
// no interruption expected
}
checkAndConfigure();
}
}
}