我一直很好奇滚动文件是如何在日志中实现的。
如何开始用任何语言创建一个文件写入类,以确保不超过文件大小。
我能想到的唯一可能的解决方案是:
write method:
size = file size + size of string to write
if(size > limit)
close the file writer
open file reader
read the file
close file reader
open file writer (clears the whole file)
remove the size from the beginning to accommodate for new string to write
write the new truncated string
write the string we received
这似乎是一个糟糕的实现,但我想不出更好的方法。
具体来说,我很想看到 Java 中的解决方案。
编辑:通过从开头删除大小,假设我有 20 字节字符串(这是限制),我想编写另一个 3 字节字符串,因此我从开头删除 3 个字节,并留下结尾17 个字节,通过附加新字符串,我有 20 个字节。
最佳答案
因为你的问题让我研究了它,所以这里有一个来自 logback
日志框架的示例。 RollingfileAppender#rollover()
方法如下所示:
public void rollover() {
synchronized (lock) {
// Note: This method needs to be synchronized because it needs exclusive
// access while it closes and then re-opens the target file.
//
// make sure to close the hereto active log file! Renaming under windows
// does not work for open files
this.closeOutputStream();
try {
rollingPolicy.rollover(); // this actually does the renaming of files
} catch (RolloverFailure rf) {
addWarn("RolloverFailure occurred. Deferring roll-over.");
// we failed to roll-over, let us not truncate and risk data loss
this.append = true;
}
try {
// update the currentlyActiveFile
currentlyActiveFile = new File(rollingPolicy.getActiveFileName());
// This will also close the file. This is OK since multiple
// close operations are safe.
// COMMENT MINE this also sets the new OutputStream for the new file
this.openFile(rollingPolicy.getActiveFileName());
} catch (IOException e) {
addError("setFile(" + fileName + ", false) call failed.", e);
}
}
}
正如您所看到的,逻辑与您发布的非常相似。他们关闭当前的 OutputStream
,执行翻转,然后打开一个新的 (openFile()
)。显然,这一切都是在同步块(synchronized block)中完成的,因为许多线程正在使用记录器,但一次只能发生一次翻转。
RollingPolicy
是关于如何执行翻转的策略,TriggeringPolicy
是关于何时执行翻转的策略。使用 logback
,您通常会根据文件大小或时间来制定这些策略。
关于java - 滚动文件实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739035/