logbackFilter机制.docx

上传人:b****8 文档编号:8978976 上传时间:2023-05-16 格式:DOCX 页数:5 大小:17.27KB
下载 相关 举报
logbackFilter机制.docx_第1页
第1页 / 共5页
logbackFilter机制.docx_第2页
第2页 / 共5页
logbackFilter机制.docx_第3页
第3页 / 共5页
logbackFilter机制.docx_第4页
第4页 / 共5页
logbackFilter机制.docx_第5页
第5页 / 共5页
亲,该文档总共5页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

logbackFilter机制.docx

《logbackFilter机制.docx》由会员分享,可在线阅读,更多相关《logbackFilter机制.docx(5页珍藏版)》请在冰点文库上搜索。

logbackFilter机制.docx

logbackFilter机制

logback-Filter机制

logback-Filter机制关键字:

logbackhttp:

//logback.qos.ch/manual/filters.html译自官方文档。

其实看看也不是很难懂,就是看过后动手写一次,可能会加强印象吧。

最近被log4j整郁闷了,针对多样化的分类输出无所适从,只能开多个写死的appender来凑合。

Aswehaveseen,logbackhasseveralbuilt-inwaysforfilteringlogrequests,includingthecontext-widefilter,logger-levelselectionruleandappenderfilters.Theseprovidehighperformancefilteringforthemostcommonlyencounteredcases.ThesefiltersarelargelyinspiredfromLinuxipchainsoriptablesastheyarecalledinmorerecentLinuxkernels.Logbackfiltersarebasedonternarylogicallowingthemtobeassembledorchainedtogethertocomposeanarbitrarilycomplexfilteringpolicy.logback提供了一些自带的过滤机制,包含上下文过滤,日志级别过滤,Appender输出过滤等。

他们提供了高性能的、满足最常用场景的过滤实现。

这些过滤机制很大程度上来源自linux中ipchains/iptables的灵感。

Logback提供的Filter可以通过三元逻辑运算来组合过滤链来实现复杂的过滤需求。

Therearetwomaintypesoffilters,namelyFilterandTurboFilter.重点是两种抽象的Filter类型,filters,TurboFilter.LogbackClassicFiltersarebasedonternarylogic.Thedecide(Object

event)methodofeachfilteriscalledinsequence.ThismethodreturnsoneoftheFilterReplyenumerationvalues,i.e.oneofFilterReply.DENY,FilterReply.NEUTRALorFilterReply.ACCEPT.IfthereturnedvalueisFilterReply.DENY,thenthelogeventisdroppedimmediatelywithoutconsultingtheremainingfilters.IfthevaluereturnedisFilterReply.NEUTRAL,thenthenextfilterinthechainisconsulted.Iftherearenofurtherfilterstoconsult,thentheloggingeventisprocessednormally.IfthereturnedvalueisFilterReply.ACCEPT,thentheloggingeventisprocessedimmediatelyskippingtheremainingfilters.过滤器是串行工作的,有3种FilterReply结果,DENY,NEUTRAL,ACCEPT.他们之间通过逻辑运算来得到最终处理过程。

ImplementingyourownFilterCreatingyourownfilterisnotdifficult.AllyouhavetodoisextendtheFilterabstractclass.Theonlymethodthatyouwillhavetoimplementisthedecide()method,allowingyoutocontentrateonlyonthebehaviourofyourfilter.Thenextclassisallittakestoimplementone'sownfilter.Allitdoesisacceptloggingeventswho'smessagecontainstheStringsample.Thefilterwillgiveaneutralresponsetoanyloggingeventwho'smessagedoesnotcontainthisString.Example6.1:

Basiccustomfilter(logback-examples/src/main/java/chapter6/SampleFilter.java)我们简单的实现过滤类,Java代码packagechapter6;importch.qos.logback.classic.spi.LoggingEvent;importch.qos.logback.core.filter.Filter;importch.qos.logback.core.spi.FilterReply;publicclassSampleFilterextendsFilter{@OverridepublicFilterReplydecide(ObjecteventObject){LoggingEventevent=(LoggingEvent)eventObject;if(event.getMessage().contains("sample")){returnFilterReply.ACCEPT;}else{returnFilterReply.NEUTRAL;}}}然后配置如下:

Xml代码<configuration><appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender"><Filterclass="chapter6.SampleFilter"/><layoutclass="ch.qos.logback.classic.PatternLayout"><pattern>%-4relative[%thread]%-5level%logger-%msg%n</pattern></layout></appender><root><appender-refref="STDOUT"/></root></configuration>LogbackFilters1.Atthemoment,therearetwofiltersthatshipwithlogback.LevelFilterprovideseventfilteringbasedonaLevelvalue.Iftheevent'slevelisequaltotheconfiguredlevel,thefilteracceptsordeniestheevent,dependingonitsconfiguration.Itallowsyoutochoosethebehaviouroflogbackforaprecisegivenlevel.级别过滤Filter。

相等判断==Xml代码<filterclass="ch.qos.logback.classic.filter.LevelFilter"><level>INFO</level><onMatch>ACCEPT</onMatch><onMismatch>DENY</onMismatch></filter>2.ThesecondfilterthatshipswithlogbackisThresholdFilter.Itisalsobasedonlevelvalue,butactsasathresholdtodenyanyrequestwhoselevelisnotequalorgreatertotheconfiguredlevel.AsampleuseoftheThresholdFilterisshownbelow.级别过滤,临界点判断,>=Xml代码<filterclass="ch.qos.logback.classic.filter.ThresholdFilter"><level>INFO</level></filter>EvaluatorFilterstakingJavaExpressions正则式。

标配文档用图标列出了可以匹配的内容,请查阅源文档页面Java代码<configuration><appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender"><filterclass="ch.qos.logback.core.filter.EvaluatorFilter"><evaluatorname="myEval"><expression>message.contains("billing")</expression></evaluator><OnMismatch>NEUTRAL</OnMismatch><OnMatch>DENY</OnMatch></filter><layout><pattern>%-4relative[%thread]%-5level%logger-%msg%n</pattern></layout></appender><rootlevel="INFO"><appender-refref="STDOUT"/></root></configuration>TurboFiltersTurboFilterobjectsallextendtheTurboFilterabstractclass.Liketheregularfilters,theyuseternarylogictoreturntheirevaluationoftheloggingevent.Overall,theyworkmuchlikethepreviouslymentionnedfilters.However,therearetwomaindifferencesbetweenFilterandTurboFilterobjects.TuboFilter跟Filter有两个主要区别:

TurboFilterobjectsaretiedtotheloggingcontext.Hence,theyarecallednotonlywhenagivenappenderisused,buteachandeverytimealoggingrequestisissued.Theirscopeiswiderthanappender-attachedfilters.1.TurboFilter会试图记录上下文环境。

因此他们会在每次logging请求产生的时候调用,而不是一个指定的appender使用时才出现。

Moreimportantly,theyarecalledbeforetheLoggingEventobjectcreation.TurboFilterobjectsdonotrequiretheinstantiationofaloggingeventtofilteraloggingrequest.Assuch,turbofiltersareintendedforhighperformancefilteringofloggingevent,evenbeforetheyarecreated2.更重要的是,TurboFilter会在日志事件对象创建前调用。

因此它具有更高性能的过滤日志事件,即使在事件被创建之前。

Java代码packagechapter6;importorg.slf4j.Marker;importorg.slf4j.MarkerFactory;importch.qos.logback.classic.Level;importch.qos.logback.classic.Logger;importch.qos.logback.classic.turbo.TurboFilter;importch.qos.logback.core.spi.FilterReply;publicclassSampleTurboFilterextendsTurboFilter{Stringmarker;MarkermarkerToAccept;@OverridepublicFilterReplydecide(Markermarker,Loggerlogger,Levellevel,Stringformat,Object[]params,Throwablet){if(!

isStarted()){returnFilterReply.NEUTRAL;}if((markerToAccept.equals(marker))){returnFilterReply.ACCEPT;}else{returnFilterReply.NEUTRAL;}}publicStringgetMarker(){returnmarker;}publicvoidsetMarker(StringmarkerStr){this.marker=markerStr;}@Overridepublicvoidstart(){if(marker!

=null&&marker.trim().length()>0){markerToAccept=MarkerFactory.getMarker(marker);super.start();}}}上例对具体的maker做了过滤,配置当然简单Xml代码<configuration><turboFilterclass="chapter6.SampleTurboFilter"><Marker>sample</Marker></turboFilter><appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender"><layoutclass="ch.qos.logback.classic.PatternLayout"><pattern>%-4relative[%thread]%-5level%logger-%msg%n</pattern></layout></appender><root><appender-refref="STDOUT"/></root></configuration>LogbackclassicshipswithseveralTurboFilterclassesreadyforuse.TheMDCFiltercheckthepresenceofagivenvalueintheMDCwhereasDynamicThresholdFilterallowsfilteringbasedonMDCkey/levelthresoldassociations.Ontheotherhand,MarkerFilterchecksforthepresenceofaspecificmarkerassociatedwiththeloggingrequest.Logback已经实现了3个基本的TurboFilter,MDCFilterDynamicThresholdFilterMarkerFilterXml代码<turboFilterclass="ch.qos.logback.classic.turbo.MDCFilter"><MDCKey>username</MDCKey><Value>sebastien</Value><OnMatch>ACCEPT</OnMatch></turboFilter><turboFilterclass="ch.qos.logback.classic.turbo.MarkerFilter"><Marker>billing</Marker><OnMatch>DENY</OnMatch></turboFilter>Logback-access记录操作

Logback-accessoffersmostofthefeaturesavailablewithlogback-classic.Filterobjectsareavailableandworkinthesamewayastheirlogback-classiccounterparts.Theyhandleaccess'implementationofloggingevents:

AccessEvent.Thus,acustomizedfilterforlogbackaccessfollowsstrictlythesamerulesasthoseforlogback-classic,exceptfortheeventtyperecievedasparameter.Ontheotherhand,TurboFilterobjectsaresupportedbylogback-access.一个可以保证所有404错误都会被记录的例子!

(这个很有效)Xml代码<configuration><appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender"><filterclass="ch.qos.logback.core.filter.EvaluatorFilter"><evaluatorname="myEval"><expression>event.getStatusCode()==404</expression></evaluator><OnMismatch>NEUTRAL</OnMismatch><OnMatch>ACCEPT</OnMatch></filter><layoutclass="ch.qos.logback.access.PatternLayout"><pattern>%h%l%u%t%r%s%b</pattern></layout></appender><appender-refref="STDOUT"/></configuration>更高级的示例:

记录不返回css资源的所有404Xml代码<configuration><appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender"><filterclass="ch.qos.logback.core.filter.EvaluatorFilter"><evaluatorname="Eval404"><expression>event.getStatusCode()==404</expression></evaluator><OnMismatch>NEUTRAL</OnMismatch><OnMatch>ACCEPT</OnMatch></filter><filterclass="ch.qos.logback.core.filter.EvaluatorFilter"><evaluatorname="EvalCSS"><expression>event.getRequestURI().contains("css")</expression></evaluator><OnMismatch>NEUTRAL</OnMismatch><OnMatch>DENY</OnMatch></filter><layoutclass="ch.qos.logback.access.PatternLayout"><pattern>%h%l%u%t%r%s%b</pattern></layout></appender><appender-refref="STDOUT"/></configuration

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 自然科学 > 物理

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2