提供了写入刷新控制
可配置编码方式
提供了静态字符流QuitWriter,异常不会抛出,会交给ErrorHandler去处理
//默认实时刷新,效率低但可保证每次输出均可写入,设为false时,若程序崩溃,尾部log可能丢失
protected boolean immediateFlush = true;
protected String encoding;
protected QuietWriter qw;
提供了字节流->字符流的转换
log输出 官方注释说明了在log输出之前做的检查或过滤操作[检查日志级别->过滤->检查当前输出状况(Appender状态、输出流、格式是否均具备)->输出]
public void append(LoggingEvent event) {
// Reminder: the nesting of calls is:
//
// doAppend()
// - check threshold
// - filter
// - append();
// - checkEntryConditions();
// - subAppend();
if(!checkEntryConditions()) {
return;
}
subAppend(event);
}
protected void subAppend(LoggingEvent event) {
this.qw.write(this.layout.format(event));//将日志格式化后输出
//依次输出异常栈
if(layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
int len = s.length;
for(int i = 0; i < len; i++) {
this.qw.write(s[i]);
this.qw.write(Layout.LINE_SEP);
}
}
}
//写入刷新控制
if(shouldFlush(event)) {
this.qw.flush();
}
}
还有一些Header、Footer的写入和输出流的关闭操作
继承了WriteAppender,将log输出到文件。这个比较简单,主要就是将父类中的输出流封装指向到文件。
protected boolean fileAppend = true;//是否覆盖
protected String fileName = null;//目标文件名
protected boolean bufferedIO = false;//是否缓冲
protected int bufferSize = 8*1024;//默认缓冲区大小
public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
LogLog.debug("setFile called: "+fileName+", "+append);
// It does not make sense to have immediate flush and bufferedIO.
if(bufferedIO) {
setImmediateFlush(false);//既然缓冲了,那意味着父类中的刷新控制为false-不进行同步刷新
}
reset();
FileOutputStream ostream = null;
try {
ostream = new FileOutputStream(fileName, append);
} catch(FileNotFoundException ex) {
String parentName = new File(fileName).getParent();
if (parentName != null) {
File parentDir = new File(parentName);
if(!parentDir.exists() && parentDir.mkdirs()) {
ostream = new FileOutputStream(fileName, append);
} else {
throw ex;
}
} else {
throw ex;
}
}
Writer fw = createWriter(ostream);//利用父类中的字节流->字符流转换方法
if(bufferedIO) {
fw = new BufferedWriter(fw, bufferSize);
}
this.setQWForFiles(fw);//实例化父类中的QuitWriter(实际在上面指向了文件输出流)
this.fileName = fileName;
this.fileAppend = append;
this.bufferedIO = bufferedIO;
this.bufferSize = bufferSize;
writeHeader();
LogLog.debug("setFile ended");
}
protected void setQWForFiles(Writer writer) {
this.qw = new QuietWriter(writer, errorHandler);
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-32111-2.html
中国可以在附近海