滚动文件实现

时间:2013-05-24 15:55:54

标签: java file logging filewriter rollingfileappender

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

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

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

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

1 个答案:

答案 0 :(得分: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块中完成的,因为许多线程正在使用记录器,但一次只能进行一次翻转。

RollingPolicy是关于如何执行翻转的政策,TriggeringPolicy是何时执行翻转。使用logback,您通常会根据文件大小或时间来制定这些策略。