2

我总是很好奇如何在日志中实现滚动文件。

甚至如何开始以任何语言创建文件编写类以确保不超过文件大小。

我能想到的唯一可能的解决方案是:

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 个字节。

4

1 回答 1

4

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,您通常将这些策略基于文件大小或时间。

于 2013-05-24T16:11:25.870 回答