扩展log4j系列[一]DailyRollingFileAppender的按分钟生成日志修改为按n分钟生成日志
复制DailyRollingFileAppender里面的源码,放在新命名的类public class MinuteRollingFileAppender extends FileAppender的里面,修改两个主要地方:
void rollOver() throws IOException {
/* Compute filename, but only if datePattern is specified */
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName+sdf.format(now);
// It is too early to roll over because we are still within the
// bounds of the current interval. Rollover will occur once the
// next interval is reached.
if (scheduledFilename.equals(datedFilename)) {
return;
}
// close current file, and rename it to datedFilename
this.closeFile();
//File target = new File(scheduledFilename);
//modify start------
Calendar rollTime = Calendar.getInstance();
rollTime.add(Calendar.MINUTE, -1);
log.debug(" ===== log4j rolled file time :" + rollTime.getTime());
String minuteLog = fileName+sdf.format(rollTime.getTime());
File target = new File(minuteLog);
//modify end------
if (target.exists()) {
target.delete();
}
File file = new File(fileName);
boolean result = file.renameTo(target);
if(result) {
LogLog.debug(fileName +" -> "+ scheduledFilename);
} else {
LogLog.error("Failed to rename ["+fileName+"] to ["+scheduledFilename+"].");
}
try {
// This will also close the file. This is OK since multiple
// close operations are safe.
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
}
catch(IOException e) {
errorHandler.error("setFile("+fileName+", false) call failed.");
}
scheduledFilename = datedFilename;
}
//下面是按每隔15分钟生成一个日志
public Date getNextCheckDate(Date now) {
this.setTime(now);
switch(type) {
case MinuteRollingFileAppender.TOP_OF_MINUTE:
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
//modify start------
this.add(Calendar.MINUTE, 15);
// modify end------
break;
default:
throw new IllegalStateException("Unknown periodicity type.");
}
return getTime();
}
//下面是在打印日志的事件里面过滤信息
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
try {
rollOver();
}
catch (IOException ioe) {
LogLog.error("rollOver() failed.", ioe);
}
}
log.debug(" == MinuteRollingFileAppender test LoggingEvent' message :" + event.getMessage());
String obj = this.layout.format(event);
//下面过滤掉空格、空行(注:linux下要加“/r/n”过滤才生效)
if (obj == null || obj.equals("")||obj.equals(" /r/n") || obj.equals(" /n"))
return;
super.subAppend(event);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。