`
sw1982
  • 浏览: 511307 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

logback-Filter机制

阅读更多

http://logback.qos.ch/manual/filters.html 译自官方文档。其实看看也不是很难懂,就是看过后动手写一次,可能会加强印象吧。最近被log4j整郁闷了, 针对多样化的分类输出无所适从,只能开多个写死的appender来凑合。

 

 

As we have seen, logback has several built-in ways for filtering log requests, including the context-wide filter, logger-level selection rule and appender filters. These provide high performance filtering for the most commonly encountered cases. These filters are largely inspired from Linux ipchains or iptables as they are called in more recent Linux kernels. Logback filters are based on ternary logic allowing them to be assembled or chained together to compose an arbitrarily complex filtering policy.

 

logback提供了一些自带的过滤机制,包含上下文过滤,日志级别过滤,Appender输出过滤等。他们提供了高性能的、满足最常用场景的过滤实现。 这些过滤机制很大程度上来源自linux中ipchains/iptables的灵感。Logback提供的Filter可以通过三元逻辑运算来组合过滤链来实现复杂的过滤需求。

 

There are two main types of filters, namely Filter and TurboFilter .

重点是两种抽象的Filter类型,filters,TurboFilter.

 

Logback Classic

 

Filter-chain

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 do is extend the Filter abstract class. The only method that you will have to implement is the decide() method, allowing you to contentrate only on the behaviour of your filter.

The next class is all it takes to implement one's own filter. All it does is accept logging events who's message contains the String sample . The filter will give a neutral response to any logging event who's message does not contain 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 {

  @Override
  public 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 a Level value. If the event's level is equal to the configured level, the filter accepts or denies the event, depending on its configuration. It allows you to choose the behaviour 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 request whose level is not equal or greater to the configured level. A sample use 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;

  @Override
  public 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;
  }

  @Override
  public 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,MDCFilter DynamicThresholdFilter MarkerFilter

  <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>
 
分享到:
评论

相关推荐

    Android-logback-android用于Android的可靠通用快速和灵活的日志记录框架

    `logback-android`支持插件机制,允许开发者编写自定义的Appender、Filter和Layout。这为日志系统提供了极高的灵活性,可以根据项目需求定制各种高级功能。 综上所述,`logback-android`作为Android开发中的日志...

    logback-1.1.2源码包

    通过深入研究 logback 的源码,开发者可以了解其内部工作机制,如何进行日志管理、配置解析、过滤和输出等。这对于自定义日志策略、优化性能或开发扩展模块都非常有价值。此外,理解 logback-classic 如何实现 SLF4J...

    logback.的jar包

    1. **logback-core**: 这是 Logback 的核心模块,提供了基本的日志处理机制,包括事件处理、配置解析以及 Appender 和 Layout 的接口定义。它为 logback-classic 和 logback-access 提供了底层支持。 2. **logback-...

    logback-0.9.24

    `logback-core-0.9.24.jar` 是 Logback 的核心组件,提供了日志基础设施,包括事件处理、异步日志记录、过滤器机制、配置解析等功能。以下是一些关键知识点: 1. **事件处理器(AppenderBase)**:是所有 Appender ...

    logback-0.9.15.zip

    - **可扩展性**:logback可以通过自定义Appender(日志输出目的地)、Layout(日志格式)和Filter(日志过滤规则)进行扩展,满足各种应用场景。 - **安全性**:提供了安全的异步日志处理,避免阻塞应用程序的主线程...

    logback官方中文版文档

    logback-core 是整个框架的基础,它提供了日志处理的基本机制。包括事件处理、配置解析、Appender(日志输出器)和 Layout(日志格式化)等核心功能。开发者可以利用这些基础组件构建自定义的日志解决方案。 **...

    logback日志框架包

    1. **logback-core**:作为基础组件,它提供了日志记录的基本机制,包括日志事件的创建、传输、过滤和存储。logback-core 是 logback-classic 和 logback-access 的基石,为整个框架提供了必要的基础设施。 2. **...

    logback文档

    过滤器(Filter)是控制日志消息是否能够被Appender处理的组件,文档中分别讲解了在logback-classic和logback-access中的过滤器使用方法。常规过滤器以及更为高级的TurboFilters和重复消息过滤器...

    logback完整学习例子

    Logback 提供了基于 Spring Profile 的环境切换机制。你可以创建多个 `logback.xml` 文件,如 `logback-dev.xml`、`logback-test.xml` 和 `logback-prod.xml`,并在每个环境中设置相应的 profile。 3. **日志生成**...

    logback.jar

    Logback设计上注重性能,它采用了异步日志记录机制,通过使用`AsyncAppender`可以在不阻塞主线程的情况下进行日志输出。此外,还可以通过配置来优化日志文件大小,例如设置日志文件的最大大小,当达到限制时自动滚动...

    SpringBoot默认日志配置说明

    对于更复杂的需求,比如日志分割、大小限制、归档等,可以通过配置不同的Appender(如`RollingFileAppender`)和Filter来实现。例如,我们可以设置每天生成一个新的日志文件,并保留30天的日志: ```xml ...

    logback filter,tree component,spring exception resolver

    例如,研究`ch.qos.logback.core.filter.Filter`类可以了解过滤器的工作机制,而深入`ch.qos.logback.classic.Logger`的源码则能揭示日志记录过程。 5. **工具应用**: 在实际开发中,我们常常结合Logback提供的...

    logback学习

    &lt;filter class="ch.qos.logback.core.filter.EvaluatorFilter"&gt; &lt;evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator"&gt; &lt;marker&gt;FATAL &lt;onMismatch&gt;DENY &lt;onMatch&gt;NEUTRAL &lt;/filter&gt; ``` 该 ...

    Logback手册中文版

    - **工作原理**:Logback的核心机制基于事件驱动模型,当应用代码调用日志方法时,会触发一系列事件处理,最终将日志消息输出到指定的appender。 - **性能**:Logback通过优化设计和实现,在性能方面表现优异,尤其...

    日志框架logback的Jar包和xml文件

    Logback的设计考虑了性能因素,例如,它使用了日志事件缓存和异步日志记录机制来提高效率。此外,通过智能配置,如只在日志级别匹配时才解析布局,避免了不必要的计算。 **五、与其他框架的集成** Logback与Spring...

    logback中文资料

    Logback提供了强大的配置机制,可以通过XML文件、JSON文件等多种方式配置。 ##### 3.1 自动配置 如果项目中没有显式的配置文件,Logback会尝试使用默认配置文件(如`logback-simple.xml`)。 ##### 3.2 配置文件...

    Logback用户手册中文版.pdf

    在Logback中,Logger是基于父子继承机制的,子Logger会继承父Logger的有效级别。 Appender负责将日志事件发送到目的地。Logback支持多种Appender,包括ConsoleAppender(控制台输出)、FileAppender(文件输出)、...

    logback测试

    4. **Filter**: 可以控制哪些日志事件被记录,提供过滤机制。 5. **Configurator**: 读取配置文件并设置 Logback 配置。 **二、配置 Logback** Logback 使用 XML 文件进行配置,通常命名为 `logback.xml`。以下是...

    logback+springboot的基本使用方式.zip

    首先,我们需要理解SpringBoot的日志处理机制。SpringBoot默认使用Logback作为日志系统,因为它是SLF4J的推荐实现。SLF4J提供了一种抽象层,允许我们切换不同的日志实现,而无需修改代码。这意味着,如果将来需要...

    Logback 异常日志减少打印内容

    它提供了高效、灵活的日志记录机制,允许开发者根据需要调整日志级别、格式和输出目的地。在某些情况下,尤其是处理异常时,Logback可能会生成大量的日志输出,这可能会导致性能问题,甚至淹没真正重要的信息。因此...

Global site tag (gtag.js) - Google Analytics