我一直很好奇滚动文件是如何在日志中实现的。
如何开始用任何语言创建一个文件写入类,以确保不超过文件大小。
我能想到的唯一可能的解决方案是:
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
由于许多线程正在使用记录器,因此会阻塞,但一次只能发生一次翻转。
A RollingPolicy
是关于如何执行滚动的策略和TriggeringPolicy
是何时执行翻转。和logback
,您通常根据文件大小或时间来制定这些策略。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)