我创建了一个appender,用文件名创建当前日期并将日志写入文件,如下所示:
filename_18052014.log
问题是我的appender应该每天00:00:00创建新文件并在那里写日志。但它没有发生,它仍然写入旧文件,并且没有创建新文件...
我的代码:
package com.comarch.log4j;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.FileAppender;
public class DateFormatFileAppender extends FileAppender {
private String fileName = "";
public DateFormatFileAppender() {
setFile("");
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException {
super.setFile(generateFileName(), append, bufferedIO, bufferSize);
}
private String generateFileName() {
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
String dateString = df.format(new Date());
return String.format("%s_%s.log", getFileName(), dateString);
}
}
你有什么想法,怎么做?
您对此解决方案有何看法?方法追加被扩展。
package com.comarch.log4j;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.FileAppender;
public class DateFormatFileAppender extends FileAppender {
private String fileName = "";
private int day;
public DateFormatFileAppender() {
setFile("");
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException {
if (!getFile().equals(""))
super.setFile(fileName, append, bufferedIO, bufferSize);
}
public void append(LoggingEvent event) {
if (Calendar.DAY_OF_MONTH != day) {
setFile(generateFileName());
activateOptions();
}
super.append(event);
}
private String generateFileName() {
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
String dateString = df.format(new Date());
return String.format("%s_%s.log", getFileName(), dateString);
}
}