后端——框架——日志框架——logback——《官网》阅读笔记——第五章节(Encoder)

  第五章节介绍核心对象Encoder,它是Layout接口的升级版,它的职责是对日志信息进行格式化。

  它的主要内容如下:

  1. 它相对于Layout接口的优点。
  2. 它的类体系结构

1、对比Layout

  以下引用原著中二者的对比

  Layoutsas discussed in detail in the next chapterare only able to transform an event into a StringMoreovergiven that a layout has no control over when events get written out, layouts cannot aggregate events into batchescontrast this with encoders which not only have total control over the format of the bytes written out, but also control when (and if) these bytes written out

  这段话的含义有三点:

  1. Encoder将events转换为bytes,而layout转换为String。
  2. Encoder完全控制日志信息的格式。
  3. Encoder完全控制日志信息何时输出到Appender。

2、类结构

父接口:

  • ContextAware将Encoder对象与LoggerContext对象绑定
  • LifeCycle生命周期接口,只有三个方法,start,stop,isStarted。

在子类中,需要了解的是LayoutWrappingEncoder和PatternLayoutEncoder类,类名最后4个字母为Base的类基本不需要了解。

  2.1 LayoutWrappingEncoder

  在本章中最开始介绍到Encoder是Layout接口的升级,通常遇到这类问题时,需要使用适配器模式。LayoutWrappingEncoder就扮演者Adapter的角色,Layout扮演Adaptee的角色,Encoder扮演Target的角色。

  它的源码如下:

public class LayoutWrappingEncoder<E> extends EncoderBase<E> {
    protected Layout<E> layout;
    private Charset charset;
    Appender<?> parent;
    Boolean immediateFlush = null;
    private byte[] convertToBytes(String s) {
        if (charset == null) {
            return s.getBytes();
        } else {
            return s.getBytes(charset);
        }
    }
    public byte[] encode(E event) {
        String txt = layout.doLayout(event);
        return convertToBytes(txt);
    }

    // 忽略了get & set相关方法
}

   从上述代码可以看到,这个类只做了一件事,就是将layout.doLayout方法返回的字符串转换为了bytes[]。

  2.2 PatternLayoutEncoder

  PatternLayoutEncoder是配置的主要对象,当配置文件中encoder标签不指定class属性时,它的默认值为PatternLayoutEncoder。

  当我们在配置encoder标签时,根据class类型的不同,子标签也不同。子标签的名称对应类的属性,子标签的文本对应属性的值。例如在encoder标签中配置了<pattern>标签,相当于给PatternLayoutEncoder对象的pattern属性赋值。

  从类结构图中,可以看出,PatternLayoutEncoder有很多父类,会继承很多属性。

  • 从EncoderBase类中继承started属性,该属性表示Encoder是否已启动。
  • 从LayoutWrappingEncoder中继承以下四个属性

属性

属性:layout

      说明:所依赖的layout对象,对应encoder子标签layout的class属性。

      值:Encoder接口的实现类。

      是否必填:否

 

属性:charset

      说明:字符集。

      值:Charset对象。

      是否必填:是,默认值为平台或编译器的字符集

 

属性:immediateFlush

      说明:配置Appender的immediateFlush属性即可。

      值:布尔值,true或者false。

      是否必填:否

 

属性:parent

      说明:父Appender,配置Appender的parent属性即可。

      值:Appender类,或Appender的name属性。

      是否必填:否

  • 从PatternLayoutEncoderBase中继承pattern和outputPatternAsHeader属性。

属性

属性:pattern

      说明:定义日志信息的格式,最重要的属性

      值:具有一定格式的字符串。

      是否必填:是

 

属性:outputPatternAsHeader

      说明:是否在日志第一行打印pattern。

      值:布尔值,true或false。

      是否必填:否,默认值为false。

  • PatternLayoutEncoder中没有自身属性。

  至此本篇内容结束,原著链接:http://logback.qos.ch/manual/encoders.html

原文地址:https://www.cnblogs.com/rain144576/p/12304495.html