highlander
highlander

Reputation: 51

How can I configure Logback to rotate files hourly for n days?

I would like to rotate the log files hourly and keep them for n days before they are replaced. Lets say for example 2 days, so that means that I should see 48 log files if the totalSizeCap is not met.

<appender name="missing_fields" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/missing_fields.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  <fileNamePattern>logs/missing_fields_%d{yyyyMMdd-HH}.log</fileNamePattern>
    <maxHistory>48</maxHistory>
    <totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
   <pattern>%date#%level#%logger#thread#%message%n%xException</pattern>
</encoder>

What I get is that log files are rotating hourly but only for 24 hours. So after that, logback starts replacing the files instead of keeping them for 48 hours.

E.g. I would expect to see: missing_field_20170104-10.log and after one day missing_field_20170105-10.log,

while it only keeps log files for 24 hours.

Upvotes: 3

Views: 6837

Answers (2)

Jhon Sal Chi Chon
Jhon Sal Chi Chon

Reputation: 27

In the official documentation you will find the following example:

<configuration>
<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>mylog.txt</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
  <!-- rollover daily -->
  <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
   <!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
   <maxFileSize>100MB</maxFileSize>    
   <maxHistory>60</maxHistory>
   <totalSizeCap>20GB</totalSizeCap>
</rollingPolicy>
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
</appender>


   <root level="DEBUG">
        <appender-ref ref="ROLLING" />
   </root>

</configuration>

Note the "%i" conversion token in addition to "%d". Both the %i and %d tokens are mandatory.

Upvotes: -1

Dmitry Gorkovets
Dmitry Gorkovets

Reputation: 2286

According to documentation you should change your config to

<maxHistory>48</maxHistory>

Upvotes: 0

Related Questions