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的優勢:

 2.Encoder接口詳解

Encoder負責把事件轉換爲字節數組,並把字節數組寫到合適的輸出流。所以,encoder能夠控制在何時、把什麼樣的字節數組寫入到其擁有者維護的輸出流中。Encoder接口有兩個實現類,LayoutWrappingEncoderPatternLayoutEncoderjava

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: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);     }
  }
}
doEncode()方法首先讓被包裹的 layout 把傳入的事件轉換成字符串,再根據用戶選擇的字符集編碼把字符串轉換成字節,而後把本身寫入其擁有者 appender 指定的輸出流,輸出 流被當即衝出(flush)。

 2.PatternLayoutEncoder類詳解

因爲PatternLayout是最經常使用的Layout,所以logback提供了PatternLayoutEncoder,它擴展了LayoutWrappingEncoder且僅使用PatternLayout編碼

注意:從logback0.9.19版起,FileAppender或其子類(好比,RollingFileAppender)在只要用到PatternLayout時,都必須換成PatternLayoutEncoder。spa

相關文章
相關標籤/搜索