Log processing is required when the SSM framework builds Java Web. I had a few problems configuring logback, so I took a closer look at logback. In addition to reading a lot of blogs, I also looked at the official logback documentation, and after reading it, I needed to record what I saw.

Let’s start with the composition of an Appender

An Appender class diagram looks like this:

ConsoleAppender

ConsoleAppender for console log output the official documentation gives an example

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <! -- encoders are assigned thetype
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
Copy the code
  • < Encoder > is used to format logs, convert them into byte arrays, and output the converted byte arrays to OutputStream. Before encoder came into being, we relied on Layout to handle log formatting.

Currently, PatternLayoutEncoder is the only really useful encoder. It simply wraps most of the work for PatternLayout. Specific see https://logback.qos.ch/manual/encoders.html

FileAppender

The FileAppender is used to save logs as files

<configuration> <! -- Insert the current time formatted as"yyyyMMdd'T'HHmmss" under
       the key "bySecond" into the logger context. This value will be
       available to all subsequent configuration elements. -->
  <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <! -- use the previously created timestamp to create a uniquely namedlog file -->
    <file>log-${bySecond}.txt</file>
    <encoder>
      <pattern>%logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
Copy the code

  • This property can be used to record the parsing time of the configuration file.

  • Records the address and file name of the file

RollingFileAppender

RollingFileAppender is an extension of FileAppender. Compared to its parent, its main purpose is to scroll through logging. RollingFileAppender has two important child components: RollingPolicy and TriggeringPolicy. RollingPolicy determines the log rolling mode, and TriggeringPolicy determines the triggering conditions for log rolling. (A RollingPolicy can also define conditions that trigger scrolling.)

RollingPolicy includes the following rolling policies:

TimeBasedRollingPolicy

Time-based rolling strategy. This is probably the most common scrolling strategy. The official document example configuration is as follows

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logFile.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! -- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <! -- keep 30 days' worth of history capped at 3GB total size --> 
      
       30
       
      
       3GB
        
       
       
        %-4relative [%thread] %-5level %logger{35} - %msg%n
        
         
       
        
       Copy the code

  • The name of the file after scrolling, including the selection of scrolling time.

  • The number of archive files retained, relative to the previous fileNamePattern. If the value is defined as 6, when fileNamePattern is in days, the logs are saved for six days. If the logs are saved in months, the logs are saved for six months. Old logs are deleted asynchronously.

  • Size of all archive logs. When the limit is exceeded, the old archive log is deleted.

SizeAndTimeBasedRollingPolicy

SizeAndTimeBasedRollingPolicy is rolling strategy based on time and file size The official document sample configuration is as follows

<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 ofhistory. 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>
Copy the code

<totalSizeCap> qualifies all archive log files, while <maxFileSize> qualifies individual log files

FixedWindowRollingPolicy

Window size based scrolling strategy. This may sound confusing, but it basically means that the maximum number of archived log files is written to the next file, and the window size is the maximum number of log files allowed. The official document example configuration is as follows

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>test.log</file>

    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>tests.%i.log.zip</fileNamePattern>
      <minIndex>1</minIndex>
      <maxIndex>3</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      <maxFileSize>5MB</maxFileSize>
    </triggeringPolicy>
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>
        
  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
Copy the code

  • Window lower limit. The lower limit is usually 1.

  • Window upper limit. Usually we just use the upper limit.

SizeBasedTriggeringPolicy

SizeBasedTriggeringPolicy is TriggeringPolicy (decide when rolling), as if for the moment, the only such a TriggeringPolicy. The main function is to roll the archive log file when it reaches a certain size. According to the Internet, and SizeBasedTriggeringPolicy TimeBasedRollingPolicy conflicts, cannot be used at the same time.

In the old version of the logback can under this rollingPolicy TimeBasedRollingPolicy configuration a timeBasedFileNamingAndTriggeringPolicy (SizeAndTimeBasedFNAT implementation class P) achieve the rolling policy of configuring both time and file size; Actually used in the new version SizeAndTimeBasedRollingPolicy can at the same time satisfy the two requirements.

Appendix:

Here is an example of how to configure an older version of an Appender:

<! Log file output --> <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}.log</File><! -- Set the log value to no more than${log.max.size}Note that if it is a Web project, it will be saved to the Tomcat bin directory --> <! -- Scroll through a file, first logging to a specified file, and then logging to another file when a condition is met. --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip </FileNamePattern> <! The log size of the current day exceeds${log.max.size}, compressed logs and save -- > < timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <! --> <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{56}.%method:%L -%msg%n</pattern>
        </layout>
    </appender>
Copy the code

The new version of SizeAndTimeBasedRollingPolicy configuration, the official sample is as follows:

<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 ofhistory. 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>
Copy the code