1

我根据这个解决方案编写了代码: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,并且我想清除最旧的行以释放新行的空间。

例子:

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.
4

1 回答 1

0

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

于 2019-01-10T09:19:19.307 回答