Logback rollingFileAppender xml not rolling over o

2019-09-10 00:53发布

问题:

Here's a part of the logback:

<appender name="APP_LOG"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${APP_HOME}/loader.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${APP_HOME}/archived/loader.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- Keep logs max for x days -->
            <maxHistory>1</maxHistory>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>

    </appender>

This should create a new log file every day. Today is Jan-13-2016, therefore if there is no log for Jan-12-2016 it should just put the current log into loader.2016-01-12.0.log and then create a new log file right? It's not doing that.

It should also be deleting the files loader.2015-12-30.0.log and loader.2016-01-11.0.log but it's not doing that either.

All I'm doing is starting the application in an Eclipse based IDE, and I can verify that the log file loader.log is changing every time the application runs. Which means logback is starting, but for some reason it's not cleaning up old files properly. Please help?

回答1:

The Logback documentation for TimeBasedRollingPolicy specifies that the unit of maxHistory is months, not days.

With regards to the creation of an empty log file (size 0) for days where no logs were created, I recall that log4j didn't create them. OOTB log rotation in log4j was passive and the triggered only when a log statement was sent to log4j in a new day.

I would assume that Logback behaves similarly, but I'm checking and I will update this answer soon.

EDIT: Confirmed. The TimeBasedRollingPolicy does not create zero-sized files for any fully elapsed intermediate days between the last log statement and the current log statement.

That is, if your last log statement with daily rotation was on 2015-01-01 and your next statement is on 2015-01-13, when the latter statement is processed, at that point Logback still would have the file for 2015-01-01 open. It would notice and it would trigger a rollover, which basically consists of:

  1. renaming the current file with the archival pattern – and –
  2. opening a new file.

But it won't create any intermediate zero-byte files.