Rolling logback logs on filesize and time

Although this is an old question, I felt that a working answer is appropriate to help anyone who requires this kind of implementation.

I use the following logback configuration to provide an HTML log, rolled over by date and filesize, as well as logging to console for debugging output.

Logfiles are stored in a logs directory with a name of logFile.html while its active, and logFile.2013-mm-dd.i.html when it rolls over, where i is the number of 50MB log files. For instance logFile.2013-01-07.0.html.

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <charset>UTF-8</charset>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{35}) - %msg %n</pattern>
    </encoder>
  </appender>

  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs\logFile.html</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- daily rollover -->
      <fileNamePattern>logs\logFile.%d{yyyy-MM-dd}.%i.html</fileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy
          class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
          <!-- or whenever the file size reaches 50MB -->
        <maxFileSize>50MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
      <!-- keep 30 days' worth of history -->
      <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
      <charset>UTF-8</charset>
      <layout class="ch.qos.logback.classic.html.HTMLLayout">
        <pattern>%d{HH:mm:ss.SSS}%thread%level%logger%line%msg</pattern>
      </layout>         
    </encoder>
  </appender> 

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
    <appender-ref ref="FILE" />     
  </root>

</configuration>

Leave a Comment