我需要每N行日志添加一个log4j页眉和页脚。我知道如何通过覆盖PatternLayout类的getHeader()/ getFooter()方法来指定log4j页眉/页脚。但是,这似乎仅限于在每个滚动日志文件中包含页眉/页脚一次(顶部/底部)(在我的情况下每天)。
谢谢!
答案 0 :(得分:2)
对布局类进行子类化是不够的。如果你也创建了自己的appender子类,我假设你的情况下是RollingFileAppender。您可以覆盖append()方法,以便将写入的行(实际上是写入的记录)计算到文件中,然后根据行数调用writeHeader()/ writeFooter()。
以下实现允许您通过headerFrequency
属性设置标头在配置文件中的写入频率:
public class MyRollingFileAppender extends RollingFileAppender {
// number of lines after which the header is written
private int headerFrequency = -1;
// Count of lines written by the appender
private int nbLines = 0;
@Override
public void append(final LoggingEvent event) {
super.append(event);
nbLines++;
if ((headerFrequency > 0) &&
(nbLines % headerFrequency == 0)) {
writeHeader();
}
}
public int getHeaderFrequency() {
return headerFrequency;
}
public void setHeaderFrequency(final int headerFrequency) {
this.headerFrequency = headerFrequency;
}
}
以下布局实现允许您实际在log4j配置文件中设置标题文本:
public class MyLayout extends PatternLayout {
// The header
private String header = null;
@Override
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
}
然后你可以在log4j配置中使用它,如下所示:
log4j.appender.CUSTOM=test.MyRollingFileAppender
log4j.appender.CUSTOM.HeaderFrequency=100
... other appender properties ...
log4j.appender.CUSTOM.layout=test.MyLayout
log4j.appender.CUSTOM.layout.Header=***** This is my header *****\n
... other layout properties ...
log4j.rootLogger=INFO, CUSTOM