java日志框架系列(6):logback框架encoder详解
1.Encoder
1.encoder功能
Encoder 负责两件事,一是把事件转换为字节数组,二是把字节数组写入输出流。
注意:在logback 0.9.19 版之前没有 encoder。
在之前的版本里,多数 appender 依靠 layout 来把事件转换成字符串并用 java.io.Writer 把字符串输出。在之前的版本里,用户需要在 FileAppender里嵌入一个 PatternLayout。而从 0.9.19 版开始,FileAppender 和其子类使用 encoder,不接受 layout。
encoder相比layout的优点:
![](https://img2018.cnblogs.com/blog/1621946/201910/1621946-20191016104321762-1316451440.png)
2.Encoder接口详解
Encoder负责把事件转换为字节数组,并把字节数组写到合适的输出流。因此,encoder可以控制在什么时候、把什么样的字节数组写入到其拥有者维护的输出流中。Encoder接口有两个实现类,LayoutWrappingEncoder与PatternLayoutEncoder。
Encoder接口代码如下:
package ch.qos.logback.core.encoder; import java.io.IOException; import java.io.OutputStream; import ch.qos.logback.core.spi.ContextAware; import ch.qos.logback.core.spi.LifeCycle; public interface Encoder<E> extends ContextAware, LifeCycle { /** * This method is called when the owning appender starts or * whenever output needs to be directed to a new OutputStream, * for instance as a result of a rollover. */ void init(OutputStream os) throws IOException; /** * Encode and write an event to the appropriate {@link OutputStream}. * Implementations are free to differ writing out of the encoded * event andinstead write in batches. */ void doEncode(E event) throws IOException; /** * This method is called prior to the closing of the underling * {@link OutputStream}. Implementations MUST not close the underlying * {@link OutputStream} which is the responsibility of the * owning appender. */ void close() throws IOException; }
1.LayoutWrappingEncoder类详解
下面通过LayoutWrappingEncoder类的部分源码,阐述如何把工作委托给Layout:
package ch.qos.logback.core.encoder;
import java.io.IOException; import java.nio.charset.Charset; import ch.qos.logback.core.Layout; public class LayoutWrappingEncoder<E> extends EncoderBase<E> { protected Layout<E> layout; private Charset charset; public void doEncode(E event) throws IOException { String txt = layout.doLayout(event); outputStream.write(convertToBytes(txt)); outputStream.flush(); } private byte[] convertToBytes(String s) { if (charset == null) { return s.getBytes(); } else { return s.getBytes(charset); }
}
}
doEncode()方法首先让被包裹的 layout 把传入的事件转换成字符串,再根据用户选择的字符集编码把字符串转换成字节,然后把自己写入其拥有者 appender 指定的输出流,输出流被立即冲出(flush)。
2.PatternLayoutEncoder类详解
由于PatternLayout是最常用的Layout,因此logback提供了PatternLayoutEncoder,它扩展了LayoutWrappingEncoder,且仅使用PatternLayout。
注意:从logback0.9.19版起,FileAppender或其子类(比如,RollingFileAppender)在只要用到PatternLayout时,都必须换成PatternLayoutEncoder。