slf4j Logger - 如果文件大小达到,则限制文件大小并删除最后n行

时间:2015-07-12 10:55:29

标签: android logging slf4j

我正在使用slf4j记录器,我遇到了一个问题:当我达到文件限制时,我不希望它启动一个新文件,但是它例如删除了一半内容并继续使用此文件。我想,主文件总是有最后的日志文件,并且总是至少有最后n个日志行!

这有可能吗?

目前我使用以下设置:

public static void init(Context context, String path, String name)
{
    // reset the default context (which may already have been initialized)
    // since we want to reconfigure it
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    // setup FileAppender
    PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
    encoder1.setContext(lc);
    encoder1.setPattern("%d{HH:mm:ss.SSS}\t%logger{36}\t%msg%n");
    encoder1.start();

    RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<ILoggingEvent>();
    rollingFileAppender.setAppend(true);
    rollingFileAppender.setContext(lc);
    rollingFileAppender.setFile(getLogFilePath(path, name));

    SizeBasedTriggeringPolicy<ILoggingEvent> triggerPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>("75kb");
    triggerPolicy.setContext(lc);
    triggerPolicy.start();
    rollingFileAppender.setTriggeringPolicy(triggerPolicy);

    FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
    rollingPolicy.setMaxIndex(1);
    rollingPolicy.setMinIndex(1);
    rollingPolicy.setContext(lc);
    rollingPolicy.setFileNamePattern(path + "/" + name + "_%i.log");
    rollingPolicy.setParent(rollingFileAppender);
    rollingPolicy.start();
    rollingFileAppender.setRollingPolicy(rollingPolicy);

    rollingFileAppender.setEncoder(encoder1);
    rollingFileAppender.start();

    // setup LogcatAppender
    PatternLayoutEncoder encoder2 = new PatternLayoutEncoder();
    encoder2.setContext(lc);
    encoder2.setPattern("%msg%n");
    encoder2.start();

    LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(lc);
    logcatAppender.setEncoder(encoder2);
    logcatAppender.start();

    // add the newly created appenders to the root logger;
    // qualify Logger to disambiguate from org.slf4j.Logger
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.addAppender(rollingFileAppender);
    root.addAppender(logcatAppender);
}

0 个答案:

没有答案