1

Using logback, and its RollingFileAppender, how can I configure a log to roll over on time and size, but also on every application launch?

The following config generates a new log file on each day, and when the previous one gets too big. However, it will not generate a new log file when the application is restarted.

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
        <maxFileSize>100MB</maxFileSize>
        <maxHistory>60</maxHistory>
        <totalSizeCap>20GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
        <pattern>%msg%n</pattern>
    </encoder>
</appender>

How can I also trigger a rollover when the application is started?

I could include the application start time in the filename pattern, by referencing

<timestamp key="startTime" datePattern="HHmmss" timeReference="contextBirth"/>

However this would screw up automatic archival and cleanup, and every subsequent log file until restart would contain that startup timestamp as well, even on the following days. Ideally I would prefer if the filenames do not contain any timestamps.

There is an old question from 2010 dealing with the same problem: How to roll the log file on startup in logback

However that question does not use SizeAndTimeBasedRollingPolicy, which did not exist at the time, and the answers do not work with the current version of logback, since the interface and the internal classes changed quite a bit since then.

HugoRune
  • 13,157
  • 7
  • 69
  • 144
  • Have you looked at the source yet? – Thorbjørn Ravn Andersen Sep 05 '21 at 20:48
  • As a last resort before posting here, sure, but without any success. The SizeAndTimeBasedRollingPolicy seems impossible to extend to trigger rollover on startup. All relevant methods are hidden in SizeAndTimeBasedFNATP, when I override isTriggeringEvent to return true on first call, i get a NullPointerException, and so on. If you see a way without reimplementing the whole thing, please let me know. – HugoRune Sep 05 '21 at 21:06
  • Last time I had to deal with this we restarted the application daily so the "single file per invocation with a time stamp and no rollover" worked for us. I then added code to a subclass of the appender that cleaned up old logs at startup which I could bring in as part of the application (logback sees the full application classpath). I have not looked at the source since. – Thorbjørn Ravn Andersen Sep 06 '21 at 16:11

0 Answers0