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
块中完成的,因为许多线程都在使用记录器,但一次只能发生一次翻转。
ARollingPolicy
是关于如何执行翻转的策略,aTriggeringPolicy
是何时执行翻转。使用logback
,您通常将这些策略基于文件大小或时间。