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的继承关系树如下图:
这里写图片描述

从关系树中,我们可以看出appender 的下层抽象类一个线程不安全的类,而所有的日志输出器都是继承该抽象类来实现的。并且每个appender的实现类都可以通过 Encoder,Filter两个对象来格式化日志输出格式以及筛选日志。
OutputStreamAppender有两个属性如下:
这里写图片描述
一个指定的是Encoder就是前面所讲的两个格式化日志输出对象中的一个,而另外一个属性是指定日志写入是否及时刷新默认值时true可以确保appender发生异常的时候日志能不遗漏的正常写入到目的地。

2.ConsoleAppender控制台输出

从上述继承树中可以看出ConsoleAppender是Appender的一个实现类,其中这个Appender的属性如下:
这里写图片描述
其中他有两个自己的属性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 这个是我们平常项目中用到最多的一种。
这里写图片描述
其中有几个比较重要的属性

  • 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的类,只是多了日志滚动功能
这里写图片描述
他比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

属性值如下
这里写图片描述
这里写图片描述
- fileNamePattern
这里写图片描述
这里写图片描述
这里写图片描述

  • 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

这里写图片描述
这里写图片描述

<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

猜你喜欢

转载自blog.csdn.net/u014297148/article/details/80377728