我编写了我的个人 log4j Daily Rolling Appender,以便为我的应用程序自定义日志记录。
这是Appender的源代码
private final static String DOT = ".";
private final static String HIPHEN = "-";
private static final String ORIG_LOG_FILE_NAME = "OrginalLogFileName";
public MigrationFilterDailyRollingFileAppender()
{
}
public MigrationFilterDailyRollingFileAppender(Layout layout, String fileName,
String datePattern)
throws IOException
{
super(layout, fileName, datePattern);
}
@Override
public void activateOptions()
{
MDC.put(ORIG_LOG_FILE_NAME, fileName);
super.activateOptions();
}
@Override
public void append(LoggingEvent event)
{
try
{
setFile(appendMigrationToFileName((String) MDC.get(ORIG_LOG_FILE_NAME)), this.getAppend(), this.getBufferedIO(),
this.getBufferSize());
}
catch (IOException ie)
{
errorHandler.error(
"Error occured while setting file for the log level "
+ event.getLevel(), ie,
ErrorCode.FILE_OPEN_FAILURE);
}
super.append(event);
}
private String appendMigrationToFileName(String oldLogFileName)
{
if (oldLogFileName != null)
{
Object obj = MDC.get("MIGRATION");
if (obj != null)
{
String level = (String)obj;
final File logFile = new File(oldLogFileName);
String newFileName = "";
final String fn = logFile.getName();
final int dotIndex = fn.indexOf(DOT);
if (dotIndex != -1)
{
// the file name has an extension. so, insert the level
// between the file name and the extension
newFileName = fn.substring(0, dotIndex) + HIPHEN + level + DOT
+ fn.substring(dotIndex + 1);
}
else
{
// the file name has no extension. So, just append the level
// at the end.
newFileName = fn + HIPHEN + level;
}
return logFile.getParent() + File.separator + newFileName;
}
else return oldLogFileName;
}
return null;
}
这是 log4j.properties
FILE 设置为 DailyRollingFileAppender
log4j.appender.FILE=MYAPPENDER
log4j.appender.FILE.Threshold=DEBUG
log4j.appender.FILE.File=${it.fastweb.activity.node.nodeHome}/log/logFile.log
log4j.appender.FILE.Append=true
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss.SSS} %-5p [%t] %-17c{1} - %m%n
其中 MYAPPENDER 是我的自定义附加程序。
现在的问题是,有时我注意到输出日志文件被截断,尽管 FILE.Append 是真的
提前致谢
问候