在log4j中使用自定义的Appender
生活随笔
收集整理的這篇文章主要介紹了
在log4j中使用自定义的Appender
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在做項目時需要把log4j的輸出轉(zhuǎn)到GUI上的一個文本框,在同學(xué)的幫助下得知可以自己繼承AppenderSkeleton類而實(shí)現(xiàn)自己對輸出的任何控制。但上網(wǎng)搜索卻無所得,所以把經(jīng)驗(yàn)共享一下。
AppenderSkeleton有一個抽象方法:
protected?abstract?void?append(LoggingEvent?event) 繼承該類并實(shí)現(xiàn)這個方法,LoggingEvent.Message中即是輸出的字符串,來參考一下WriterAppender的實(shí)現(xiàn):
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?(this.immediateFlush)?{
????this.qw.flush();
??}
}
可以看到主要就是this.qw.write(this.layout.format(event));這一行。反正主要的信息都在event里,需要什么都可以從中去取。
寫好自已的類后就可以在log4j.properties配置文件中把log4j.appender的值賦為該類名。然后log4j啟動讀入配置文件就會使用自定義的Appender了!
AppenderSkeleton有一個抽象方法:
protected?abstract?void?append(LoggingEvent?event) 繼承該類并實(shí)現(xiàn)這個方法,LoggingEvent.Message中即是輸出的字符串,來參考一下WriterAppender的實(shí)現(xiàn):
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?(this.immediateFlush)?{
????this.qw.flush();
??}
}
可以看到主要就是this.qw.write(this.layout.format(event));這一行。反正主要的信息都在event里,需要什么都可以從中去取。
寫好自已的類后就可以在log4j.properties配置文件中把log4j.appender的值賦為該類名。然后log4j啟動讀入配置文件就會使用自定義的Appender了!
轉(zhuǎn)載于:https://www.cnblogs.com/wonderow/archive/2005/05/18/158554.html
總結(jié)
以上是生活随笔為你收集整理的在log4j中使用自定义的Appender的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Delphi 控制摄像头
- 下一篇: [原创] nunit2report V1