sw1982 发表于 2013-1-29 23:19:43

logback-Filter机制

http://logback.qos.ch/manual/filters.html 译自官方文档。其实看看也不是很难懂,就是看过后动手写一次,可能会加强印象吧。最近被log4j整郁闷了, 针对多样化的分类输出无所适从,只能开多个写死的appender来凑合。
 
 
As we have seen, logback has several built-in ways forfiltering log requests, including the context-wide filter,logger-level selection rule and appender filters.These providehigh performance filtering for the most commonly encounteredcases. These filters are largely inspired from Linux ipchains oriptables as they are called in more recent Linux kernels.Logback filters are based on ternary logic allowing them to beassembled or chained together to compose an arbitrarily complexfiltering policy.
 
logback提供了一些自带的过滤机制,包含上下文过滤,日志级别过滤,Appender输出过滤等。他们提供了高性能的、满足最常用场景的过滤实现。 这些过滤机制很大程度上来源自linux中ipchains/iptables的灵感。Logback提供的Filter可以通过三元逻辑运算来组合过滤链来实现复杂的过滤需求。
 
There are two main types of filters, namely Filter and TurboFilter.
重点是两种抽象的Filter类型,filters,TurboFilter.
 
Logback Classic

 
http://logback.qos.ch/manual/images/chapter6/filterChain.gif
Filters are based on ternary logic. The decide(Object    event) method of each filter is called in sequence.This    method returns one of the FilterReply    enumeration values, i.e. one of FilterReply.DENY,    FilterReply.NEUTRAL or    FilterReply.ACCEPT.If the returned value is    FilterReply.DENY, then the log event is dropped    immediately without consulting the remaining filters. If the value    returned is FilterReply.NEUTRAL, then the next filter    in the chain is consulted. If there are no further filters to    consult, then the logging event is processed normally.If the    returned value is FilterReply.ACCEPT, then the    logging event is processed immediately skipping the remaining    filters.   
 
过滤器是串行工作的,有3种FilterReply结果,DENY,NEUTRAL,ACCEPT.他们之间通过逻辑运算来得到最终处理过程。
 
Implementing your own Filter

Creating your own filter is not difficult. All you have to dois extend the Filter abstract class. The only methodthat you will have to implement is the decide()method, allowing you to contentrate only on the behaviour of yourfilter.
The next class is all it takes to implement one's ownfilter. All it does is accept logging events who's messagecontains the String sample. The filter will give aneutral response to any logging event who's message does notcontain this String.
Example 6.1: Basic custom filter (logback-examples/src/main/java/chapter6/SampleFilter.java)
我们简单的实现过滤类,
package chapter6;import ch.qos.logback.classic.spi.LoggingEvent;import ch.qos.logback.core.filter.Filter;import ch.qos.logback.core.spi.FilterReply;public class SampleFilter extends Filter {@Overridepublic FilterReply decide(Object eventObject) {    LoggingEvent event = (LoggingEvent)eventObject;      if (event.getMessage().contains("sample")) {      return FilterReply.ACCEPT;    } else {      return FilterReply.NEUTRAL;    }}} 然后配置如下:
<configuration><appender name="STDOUT"    class="ch.qos.logback.core.ConsoleAppender">    <Filter class="chapter6.SampleFilter" />    <layout class="ch.qos.logback.classic.PatternLayout">      <pattern>      %-4relative [%thread] %-5level %logger - %msg%n      </pattern>    </layout></appender>          <root>    <appender-ref ref="STDOUT" /></root></configuration> 
Logback Filters

1.At the moment, there are two filters that ship with logback. LevelFilter provides event filtering based on aLevel value.If the event's level is equal to theconfigured level, the filter accepts or denies the event,depending on its configuration. It allows you to choose thebehaviour of logback for a precise given level.  级别过滤Filter。相等判断==
    <filter class="ch.qos.logback.classic.filter.LevelFilter">      <level>INFO</level>      <onMatch>ACCEPT</onMatch>      <onMismatch>DENY</onMismatch>    </filter> 2.The second filter that ships with logback is ThresholdFilter.It is also based on level value, but acts as a threshold to deny any requestwhose level is not equal or greater to the configured level. A sampleuse of the ThresholdFilter is shown below. 级别过滤,临界点判断,>=
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">      <level>INFO</level>    </filter> Evaluator Filters taking Java Expressions 正则式。。标配

文档用图标列出了可以匹配的内容,请查阅源文档页面
<configuration><appender name="STDOUT"    class="ch.qos.logback.core.ConsoleAppender">    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      <evaluator name="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><root level="INFO">    <appender-ref ref="STDOUT" /></root></configuration> TurboFilters

TurboFilter objects all extend the    TurboFilter abstract class. Like the regular    filters, they use ternary logic to return their evaluation of    the logging event.   
Overall, they work much like the previously mentionned    filters. However, there are two main differences between    Filter and TurboFilter objects.   
TuboFilter跟Filter有两个主要区别:
 
TurboFilter objects are tied to the logging   context. Hence, they are called not only when a given appender is   used, but each and every time a logging request is issued. Their   scope is wider than appender-attached filters.   
1.TurboFilter会试图记录上下文环境。因此他们会在每次logging请求产生的时候调用,而不是一个指定的appender使用时才出现。
 
More importantly, they are called before the   LoggingEvent object creation.   TurboFilter objects do not require the instantiation   of a logging event to filter a logging request. As such, turbo   filters are intended for high performance filtering of logging   event, even before they are created
2.更重要的是,TurboFilter会在日志事件对象创建前调用。因此它具有更高性能的过滤日志事件,即使在事件被创建之前。
package chapter6;import org.slf4j.Marker;import org.slf4j.MarkerFactory;import ch.qos.logback.classic.Level;import ch.qos.logback.classic.Logger;import ch.qos.logback.classic.turbo.TurboFilter;import ch.qos.logback.core.spi.FilterReply;public class SampleTurboFilter extends TurboFilter {String marker;Marker markerToAccept;@Overridepublic FilterReply decide(Marker marker, Logger logger, Level level,      String format, Object[] params, Throwable t) {    if (!isStarted()) {      return FilterReply.NEUTRAL;    }    if ((markerToAccept.equals(marker))) {      return FilterReply.ACCEPT;    } else {      return FilterReply.NEUTRAL;    }}public String getMarker() {    return marker;}public void setMarker(String markerStr) {    this.marker = markerStr;}@Overridepublic void start() {    if (marker != null && marker.trim().length() > 0) {      markerToAccept = MarkerFactory.getMarker(marker);      super.start();   }}} 上例对具体的maker做了过滤,配置当然简单
<configuration><turboFilter class="chapter6.SampleTurboFilter">    <Marker>sample</Marker></turboFilter><appender name="STDOUT"    class="ch.qos.logback.core.ConsoleAppender">    <layout class="ch.qos.logback.classic.PatternLayout">      <pattern>      %-4relative [%thread] %-5level %logger - %msg%n      </pattern>    </layout></appender><root>    <appender-ref ref="STDOUT" /></root></configuration> Logback classic ships with several TurboFilter   classes ready for use.The MDCFilter   check the presence of a given value in the MDC whereas DynamicThresholdFilter   allows filtering based on MDC key/level thresold associations. On   the other hand, MarkerFilter   checks for the presence of a specific marker associated with the   logging request.   
 
Logback已经实现了3个基本的TurboFilter,MDCFilterDynamicThresholdFilterMarkerFilter
<turboFilter class="ch.qos.logback.classic.turbo.MDCFilter">    <MDCKey>username</MDCKey>    <Value>sebastien</Value>    <OnMatch>ACCEPT</OnMatch></turboFilter>          <turboFilter class="ch.qos.logback.classic.turbo.MarkerFilter">    <Marker>billing</Marker>    <OnMatch>DENY</OnMatch></turboFilter> Logback-access 记录操作


Logback-access offers most of the features available with    logback-classic. Filter objects are available and    work in the same way as their logback-classic counterparts. They    handle access' implementation of logging events:    AccessEvent.Thus, a customized filter for logback    access follows strictly the same rules as those for    logback-classic, except for the event type recieved as parameter.    On the other hand, TurboFilter objects are supported    by logback-access.   
 
一个可以保证所有404错误都会被记录的例子!!(这个很有效)
<configuration><appender name="STDOUT"    class="ch.qos.logback.core.ConsoleAppender">    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      <evaluator name="myEval">      <expression>event.getStatusCode() == 404</expression>      </evaluator>      <OnMismatch>NEUTRAL</OnMismatch>      <OnMatch>ACCEPT</OnMatch>    </filter>    <layout class="ch.qos.logback.access.PatternLayout">      <pattern>      %h %l %u %t %r %s %b      </pattern>    </layout></appender><appender-ref ref="STDOUT" /></configuration> 更高级的示例:记录不返回css资源的所有404
<configuration><appender name="STDOUT"    class="ch.qos.logback.core.ConsoleAppender">    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      <evaluator name="Eval404">      <expression>event.getStatusCode() == 404</expression>      </evaluator>      <OnMismatch>NEUTRAL</OnMismatch>      <OnMatch>ACCEPT</OnMatch>    </filter>    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      <evaluator name="EvalCSS">      <expression>event.getRequestURI().contains("css")</expression>      </evaluator>      <OnMismatch>NEUTRAL</OnMismatch>      <OnMatch>DENY</OnMatch>    </filter>    <layout class="ch.qos.logback.access.PatternLayout">      <pattern>      %h %l %u %t %r %s %b      </pattern>    </layout></appender><appender-ref ref="STDOUT" /></configuration>
页: [1]
查看完整版本: logback-Filter机制