上一篇轉載了用log4j來實現同時按照日期和大小來分隔日誌,後來又研究了下log4j的升級版logback,用logback也來實現同時按照日期和大小來分隔日誌,話不多說,直接上配置檔案:

<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>

這是從官方文件上直接摘抄下來的,地址:https://logback.qos.ch/manual/appenders.html

Sometimes you may wish to archive files essentially by date but at the same time limit the size of each log file, in particular if post-processing tools impose size limits on the log files. In order to address this requirement, logback ships with SizeAndTimeBasedRollingPolicy.

有時候你本來是希望按照日期來對日誌進行歸檔,但是同時你又希望限制每個日誌檔案的大小,為了滿足這一需求,logback提供了SizeAndTimeBasedRollingPolicy.

按照官網說明根據你想每天,每個小時甚至每分鐘都生成一個新的日誌檔案,並且按照檔案大小來分隔,都是可以的,沒問題的。

附:經過測試,簡單寫10w條資料,發現按照大小分割的時候並沒有log4j那麼精確,比如我按照2MB來分割,log4j基本上在2048K左右就會進行分割,但是logback有可能在2.1M,2.5M左右進行分割。還有寫日誌總共用時也略微高於log4j。(⊙﹏⊙)(⊙﹏⊙)

pom依賴備忘:

<dependency>
		  <groupId>ch.qos.logback</groupId>
		  <artifactId>logback-core</artifactId>
		  <version>1.1.8</version>
		</dependency>
		<dependency>
		  <groupId>ch.qos.logback</groupId>
		  <artifactId>logback-classic</artifactId>
		  <version>1.1.8</version>
		</dependency>
		<dependency>
		  <groupId>ch.qos.logback</groupId>
		  <artifactId>logback-access</artifactId>
		  <version>1.1.7</version>
		</dependency>