1. 程式人生 > >Logback:同時按照日期和大小分割日誌(最新日誌可以不帶日期或數字)

Logback:同時按照日期和大小分割日誌(最新日誌可以不帶日期或數字)

Maven座標

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

 

官網說明:Size and time based rolling policy

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.

Note that TimeBasedRollingPolicy already allows limiting the combined size of archived log files. If you only wish to limit the combined size of log archives, then TimeBasedRollingPolicy

 described above and setting the totalSizeCap property should be amply sufficent.

注意,TimeBasedRollingPolicy已經允許限制合併歸檔日誌檔案的大小。如果你只希望限制合併歸檔日誌的大小,TimeBasedRollingPolicy中設定totalSizeCap即可:

Here is a sample configuration file demonstrating time and size based log file archiving.

Example: Sample configuration for SizeAndTimeBasedFNATP (logback-examples/src/main/resources/chapters/appenders/conf/logback-sizeAndTime.xml)

下面是一個示例配置檔案說明基於時間和大小的日誌檔案歸檔。      

View as .groovy

<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. Each time the current log file reaches maxFileSize before the current time period ends, it will be archived with an increasing index, starting at 0.

注意:“%i"”轉換標記除了“% d”。%i"和% d令牌都是強制性的。每次當前日誌檔案之前到達maxFileSize當前時間段結束時,它將存檔增加索引從0開始。

Size and time based archiving supports deletion of old archive files. You need to specify the number of periods to preserve with the maxHistory property. When your application is stopped and restarted, logging will continue at the correct location, i.e. at the largest index number for the current period.

基於大小和時間的歸檔支援刪除舊存檔檔案。您需要指定使用maxHistory屬性保留的時期數量。當應用程式停止並重新啟動時,日誌記錄將在正確的位置繼續,即當前期間的最大索引號。

In versions prior to 1.1.7, this document mentioned a component called SizeAndTimeBasedFNATP. However, given that SizeAndTimeBasedFNATP offers a simpler configuration structure, we no longer document SizeAndTimeBasedFNATP. Nevertheless, earlier configuration files using SizeAndTimeBasedFNATP will continue to work just fine. In fact,SizeAndTimeBasedRollingPolicy is implemented with a SizeAndTimeBasedFNATP subcomponent.

 

在1.1.7之前的版本中,本文件提到了一個名為SizeAndTimeBasedFNATP的元件。但是,考慮到SizeAndTimeBasedFNATP提供了更簡單的配置結構,我們不再記錄SizeAndTimeBasedFNATP。不過,使用SizeAndTimeBasedFNATP的早期配置檔案將繼續正常工作。實際上,SizeAndTimeBasedRollingPolicy是用SizeAndTimeBasedFNATP子元件實現的。

Logback.xml:同時按照日期和大小分割日誌

有兩種形式:
最新的日誌,是日期最大數字最大的
最新的日誌,是沒有日期沒有數字的
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定義日誌檔案的儲存地址 -->
    <property name="LOG_HOME" value="/usr/local/java/tomcat-log/專案名" />

    <!-- 控制檯輸出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化輸出:%d表示日期,%thread表示執行緒名,%-5level:級別從左顯示5個字元寬度%msg:日誌訊息,%n是換行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 按照每天和固定大小(5MB)生成日誌檔案【最新的日誌,是日期最大數字最大的】 -->
   <!-- <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            &lt;!&ndash;日誌檔案輸出的檔名&ndash;&gt;
            <FileNamePattern>${LOG_HOME}/專案名_%d{yyyy-MM-dd}.%i.log</FileNamePattern>
            &lt;!&ndash;日誌檔案保留天數&ndash;&gt;
            <MaxHistory>30</MaxHistory>
            &lt;!&ndash;日誌檔案最大的大小&ndash;&gt;
            <MaxFileSize>5MB</MaxFileSize>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            &lt;!&ndash;格式化輸出:%d表示日期,%thread表示執行緒名,%-5level:級別從左顯示5個字元寬度%msg:日誌訊息,%n是換行符&ndash;&gt;
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        &lt;!&ndash;日誌檔案最大的大小&ndash;&gt;
        &lt;!&ndash;<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            &lt;!&ndash;<MaxFileSize>5MB</MaxFileSize>&ndash;&gt;
            <MaxFileSize>5KB</MaxFileSize>
        </triggeringPolicy>&ndash;&gt;
    </appender>-->

    <!-- 按照每天和固定大小(5MB)生成日誌檔案【最新的日誌,是沒有日期沒有數字的】 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_HOME}/專案名.log</file>
        <append>true</append>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/專案名_%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <!--日誌檔案保留天數-->
            <MaxHistory>30</MaxHistory>
            <!--日誌檔案最大的大小-->
            <MaxFileSize>5MB</MaxFileSize>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化輸出:%d表示日期,%thread表示執行緒名,%-5level:級別從左顯示5個字元寬度%msg:日誌訊息,%n是換行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
       <!-- <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>TRACE</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
    </appender>

    <!-- show parameters for hibernate sql 專為 Hibernate 定製 -->
    <logger name="org.hibernate.type.descriptor.sql.BasicBinder"  level="WARN" />
    <logger name="org.hibernate.type.descriptor.sql.BasicExtractor"  level="WARN" />
    <logger name="org.hibernate.SQL" level="WARN" />
    <logger name="org.hibernate.engine.QueryParameters" level="WARN" />
    <logger name="org.hibernate.engine.query.HQLQueryPlan" level="WARN" />

    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="WARN"/>
    <logger name="java.sql.Connection" level="WARN"/>
    <logger name="java.sql.Statement" level="WARN"/>
    <logger name="java.sql.PreparedStatement" level="WARN"/>


    <!--newcapec-->
    <logger name="com.newcapec" level="INFO"/>

    <!-- 日誌輸出級別 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

    <!--日誌非同步到資料庫 -->
    <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
    <!--&lt;!&ndash;日誌非同步到資料庫 &ndash;&gt;-->
    <!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
    <!--&lt;!&ndash;連線池 &ndash;&gt;-->
    <!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
    <!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
    <!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
    <!--<user>root</user>-->
    <!--<password>root</password>-->
    <!--</dataSource>-->
    <!--</connectionSource>-->
    <!--</appender>-->
</configuration>

最新的日誌,是日期最大數字最大的

最新的日誌,是沒有日期沒有數字的

Java程式使用

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private final Logger log = LoggerFactory.getLogger(this.getClass());