天天看點

Log 之Appenders

1.appender的簡介

Logback的Appender官方文檔

Logback delegates the task of writing a logging event to components called appenders. Appenders must implement the ch.qos.logback.core.Appender interface. The salient methods of this interface are summarized below:

通過官方文檔中的一段簡介,可以看出 logback 将日志寫入事件委托給名叫 appender的接口。

Appenders are ultimately responsible for outputting logging events. However, they may delegate the actual formatting of the event to a Layout or to an Encoder object. Each layout/encoder is associated with one and only one appender, referred to as the owning appender. Some appenders have a built-in or fixed event format. Consequently, they do not require nor have a layout/encoder. For example, the SocketAppender simply serializes logging events before transmitting them over the wire.

這個段引用又指出,appender裡面可以有 Layout或者Encoder兩個對象中的一個對象來指定日志輸出格式,并且這兩個對象隻一對一的關聯appender。 但是如果appender内置格式輸出或者采用混合日志格式輸出的話是可以不指定layout/encoer。是以某個appender沒有layout/encoder也是可以的。

appender的繼承關系樹如下圖:

Log 之Appenders

從關系樹中,我們可以看出appender 的下層抽象類一個線程不安全的類,而所有的日志輸出器都是繼承該抽象類來實作的。并且每個appender的實作類都可以通過 Encoder,Filter兩個對象來格式化日志輸出格式以及篩選日志。

OutputStreamAppender有兩個屬性如下:

Log 之Appenders

一個指定的是Encoder就是前面所講的兩個格式化日志輸出對象中的一個,而另外一個屬性是指定日志寫入是否及時重新整理預設值時true可以確定appender發生異常的時候日志能不遺漏的正常寫入到目的地。

2.ConsoleAppender控制台輸出

從上述繼承樹中可以看出ConsoleAppender是Appender的一個實作類,其中這個Appender的屬性如下:

Log 之Appenders

其中他有兩個自己的屬性target 以及withJansi。

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         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>
           

3.FileAppender控制台輸出

FileAppender 這個是我們平常項目中用到最多的一種。

Log 之Appenders

其中有幾個比較重要的屬性

  • append boolean 類型表示該日志檔案是否啟用追加功能,預設true,如果指定為false的話,當容器重新開機或者伺服器重新開機時會生成新的日志檔案把原有的覆寫
  • file 日志檔案的存儲路徑,在window下要将

    \

    變成

    \\

  • prudent boolean 預設false 前面可以看出appender預設是不安全的,當多個線程操作同一個日志檔案的時候可能會造成資料 不同步。可以根據需求設為true。
<configuration>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>testFile.log</file>
    <append>true</append>
    <!-- set immediateFlush to false for much higher logging throughput -->
    <immediateFlush>true</immediateFlush>
    <!-- encoders are assigned the type
         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="FILE" />
  </root>
</configuration>
           

并且FileAppender根據日志壓縮或者命名的方式又可以分為以下幾種FileAppender。

3.1 獨一無二的命名方式(時間戳)

在配置檔案中可以用

<timestamp>

标簽來初始化一個全局變量。如下配置

<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
         named log file -->
    <file>log-${bySecond}.txt</file>
    <encoder>
      <pattern>%logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
           
The timestamp element takes two mandatory attributes key and datePattern and an optional timeReference attribute. The key attribute is the name of the key under which the timestamp will be available to subsequent configuration elements as a variable. The datePattern attribute denotes the date pattern used to convert the current time (at which the configuration file is parsed) into a string. The date pattern should follow the conventions defined in SimpleDateFormat. The timeReference attribute denotes the time reference for the time stamp. The default is the interpretation/parsing time of the configuration file, i.e. the current time. However, under certain circumstances it might be useful to use the context birth time as time reference. This can be accomplished by setting the timeReference attribute to “contextBirth”.

從這段引用中我們可以看出

<timestamp>

有三個屬性

  • key 變量名
  • datePattern 時間格式
  • timeReference 開始時間的參照,預設是目前時間。可以timeReference=“contextBirth”操作容器啟動的時間。

3.2 RollingFileAppender

RollingFileAppender 是extends FileAppender的類,隻是多了日志滾動功能

Log 之Appenders

他比FileAppender多了兩個屬性RollinPolicy以及TriggeringPolicy兩個屬性,其中一個是日志滾動政策,一個是觸發滾動政策。

a RollingFileAppender must have both a RollingPolicy and a TriggeringPolicy set up.However, if its RollingPolicy also implements the TriggeringPolicy interface, then only the former needs to be specified explicitly. 從字面意思說要使用RollingFileAppender 的話 滾動政策以及觸發條件兩個是必須設定的。但是有時滾動政策實作了觸發條件的接口的話,就隻要設定滾動政策就可以了。

3.2.1滾動政策

3.2.1.1 TimeBasedRollingPolicy

屬性值如下

Log 之Appenders
Log 之Appenders

- fileNamePattern

Log 之Appenders
Log 之Appenders
Log 之Appenders
  • maxHistory 定義存儲有效日志檔案的最大數量。如根據day來滾動 那麼其儲存的就是目前日期往前推maxHistory的天數的日志數量。
  • totalSizeCap 定義目前有效日志的總大小。
  • cleanHistoryOnStart是否清除曆史日志。預設false。
<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 -->
      <maxHistory>30</maxHistory>
      <totalSizeCap>3GB</totalSizeCap>

    </rollingPolicy>

    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender> 

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
           
3.2.1.2 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.

有的時候我們又想讓日志按day來滾動,同時又想限制目前每個日志檔案的大小來友善 運維查詢日志避免日志太大打不開的情況,就可以采用大小and日期滾動政策。

這個政策比上面的多了一個屬性

  • maxFileSize單個日志檔案的最大大小。
<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>
           
3.2.1.3 FixedWindowRollingPolicy
Log 之Appenders
Log 之Appenders
<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>
           

3.2.2觸發政策

3.2.2.1 SizeBasedTriggeringPolicy
SizeBasedTriggeringPolicy accepts only one parameter, namely maxFileSize, with a default value of 10 MB.

The maxFileSize option can be specified in bytes, kilobytes, megabytes or gigabytes by suffixing a numeric value with KB, MB and respectively GB. For example, 5000000, 5000KB, 5MB and 2GB are all valid values, with the first three being equivalent.

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>test.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>test.%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>
           
3.2.2.2

4.SocketAppender and SSLSocketAppender

後期實踐後介紹

5.SMTPAppender

6.DBAppender