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