如何使用 logback 从日志文件中删除最旧的行?

How to delete the oldest lines from log file using logback?

我根据这个解决方案编写了代码:https://gist.github.com/umangmathur92/a65f67c01e2b425289b8

        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        lc.reset();
        final String LOG_DIR = context.getExternalCacheDir() + File.separator + ".ts";
        RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<>();
        rollingFileAppender.setAppend(true);
        rollingFileAppender.setContext(lc);
        rollingFileAppender.setLazy(true);
        rollingFileAppender.setFile(LOG_DIR + File.separator + "ts.log");
        SizeBasedTriggeringPolicy<ILoggingEvent> trigPolicy = new SizeBasedTriggeringPolicy<>();
        trigPolicy.setMaxFileSize(new FileSize(1024 * 256));
        trigPolicy.setContext(lc);
        trigPolicy.start();
        FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
        rollingPolicy.setContext(lc);
        rollingPolicy.setParent(rollingFileAppender);
        rollingPolicy.setFileNamePattern(LOG_DIR + File.separator + "ts.%i.log");
        rollingPolicy.setMinIndex(1);
        rollingPolicy.setMaxIndex(1);
        rollingPolicy.start();
        rollingFileAppender.setTriggeringPolicy(trigPolicy);
        rollingFileAppender.setRollingPolicy(rollingPolicy);
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setPattern("%msg%n");
        encoder.setContext(lc);
        encoder.start();
        rollingFileAppender.setEncoder(encoder);
        rollingFileAppender.start();
        ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.addAppender(rollingFileAppender);

但这不是我想做的。此代码在达到指定限制时删除所有文件并开始写入一个新文件(因此,在达到 256KB 限制文件后占用 10KB ,例如 )。

我想将文件大小限制为 256KB,并且我想清除最旧的行以发布 space 新行。

示例:

Line 1 sample text.
Line 2 sample text.
Line 3 sample text.
Line 4 sample text.
Line 5 sample text.

想象一下,这些行占用 256KB,当我写新行时:

Line 6 sample text.

我希望这个文件看起来像:

Line 2 sample text.
Line 3 sample text.
Line 4 sample text.
Line 5 sample text.
Line 6 sample text.

只要从开头删除一行,就需要重写整个文件。因此,这将是一个性能瓶颈。通常的解决方案是在旧的日志文件达到一定大小时启动一个新的日志文件。