Encoder负责把事件转换为字节数组,并把字节数组写到合适的输出流。所以,encoder能够控制在何时、把什么样的字节数组写入到其拥有者维护的输出流中。Encoder接口有两个实现类,LayoutWrappingEncoder与PatternLayoutEncoder。java
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; }
下面经过LayoutWrappingEncoder类的部分源码,阐述如何把工做委托给Layout:app
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); }
}
}
因为PatternLayout是最经常使用的Layout,所以logback提供了PatternLayoutEncoder,它扩展了LayoutWrappingEncoder,且仅使用PatternLayout。编码
注意:从logback0.9.19版起,FileAppender或其子类(好比,RollingFileAppender)在只要用到PatternLayout时,都必须换成PatternLayoutEncoder。spa