运行时切换Log4j日志策略

要实现运行时切换日志策略,需要使用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

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();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值