我正在使用java.util.logging生成日志文件。它利用FileHandler将记录写入日志文件。FileHandler类包含限制参数,以决定何时在当前日志文件的大小(以字节为单位)超过限制的情况下创建新文件。
我们是否可以重写将文件处理程序限制为其他参数而不是大小的行为?例如-在每个日志文件中最大的N个记录数。如果有(N+1)记录,将生成一个新的文件日志文件。如果不能使用标准的java.logging实现,是否还有其他开源实现这种行为(比如log4j或任何其他开源记录器)?
发布于 2017-12-18 15:41:26
可以通过重写FileHandler方法来扩展setLevel以侦听旋转。然后,通过将限制设置为一个字节,强制FileHandler始终旋转,然后如果不满足条件,则防止旋转发生。
下面是一个示例解决方案:
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
public class CountingFileHandler extends FileHandler {
private static final RuntimeException PREVENT_ROTATE = new RuntimeException();
private final long maxRecords;
private long count;
public CountingFileHandler(String pattern, long maxRecords, int files) throws IOException {
super(pattern, 1, files, false);
this.maxRecords = maxRecords;
}
@Override
public synchronized void setLevel(Level lvl) {
if (Level.OFF.equals(lvl)) { //Rotation sets the level to OFF.
if (++count < maxRecords) {
throw PREVENT_ROTATE;
}
count = 0L;
}
super.setLevel(lvl);
}
@Override
public synchronized void publish(LogRecord record) {
try {
super.publish(record);
} catch (RuntimeException re) {
if (re != PREVENT_ROTATE) {
throw re;
}
}
}
public static void main(String[] args) throws Exception {
System.out.println(new File(".").getCanonicalPath());
CountingFileHandler cfh = new CountingFileHandler("test%g.log", 2, 5);
cfh.setFormatter(new SimpleFormatter());
for (int i = 0; i < 10; i++) {
cfh.publish(new LogRecord(Level.SEVERE, Integer.toString(i)));
}
cfh.close();
}
}否则,如果您只想要一个日志文件的最大限制,您可以只安装com.sun.mail.util.logging.DurationFilter的持续时间为Long.MAX_VALUE。该过滤器包含在logging-mailhandler.jar中。这个解决方案不会提供你想要的轮换。
https://stackoverflow.com/questions/47845068
复制相似问题