logback使用MDCFilter日志过滤源码解读
作者:codecraft
这篇文章主要介绍了logback使用MDCFilter日志过滤源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
序
本文主要研究一下logback的MDCFilter
MatchingFilter
ch/qos/logback/classic/turbo/MatchingFilter.java
public abstract class MatchingFilter extends TurboFilter { protected FilterReply onMatch = FilterReply.NEUTRAL; protected FilterReply onMismatch = FilterReply.NEUTRAL; final public void setOnMatch(String action) { if ("NEUTRAL".equals(action)) { onMatch = FilterReply.NEUTRAL; } else if ("ACCEPT".equals(action)) { onMatch = FilterReply.ACCEPT; } else if ("DENY".equals(action)) { onMatch = FilterReply.DENY; } } final public void setOnMismatch(String action) { if ("NEUTRAL".equals(action)) { onMismatch = FilterReply.NEUTRAL; } else if ("ACCEPT".equals(action)) { onMismatch = FilterReply.ACCEPT; } else if ("DENY".equals(action)) { onMismatch = FilterReply.DENY; } } }
MatchingFilter继承了TurboFilter,它提供了setOnMatch及setOnMismatch方法,它们在action为NEUTRAL、ACCEPT、DENY时设置对应的onMatch、onMismatch
MDCFilter
ch/qos/logback/classic/turbo/MDCFilter.java
public class MDCFilter extends MatchingFilter { String MDCKey; String value; @Override public void start() { int errorCount = 0; if (value == null) { addError("\'value\' parameter is mandatory. Cannot start."); errorCount++; } if (MDCKey == null) { addError("\'MDCKey\' parameter is mandatory. Cannot start."); errorCount++; } if (errorCount == 0) this.start = true; } @Override public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { if (!isStarted()) { return FilterReply.NEUTRAL; } String value = MDC.get(MDCKey); if (this.value.equals(value)) { return onMatch; } return onMismatch; } public void setValue(String value) { this.value = value; } public void setMDCKey(String MDCKey) { this.MDCKey = MDCKey; } }
MDCFilter继承了MatchingFilter,其start方法校验MDCKey及value属性是否有值,其decide方法跟从MDC获取指定key的值,然后判断该值域value是否相等,相等则返回onMatch,否则返回onMismatch
示例
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <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> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%date [%thread] %-5level %logger - %msg%n</Pattern> </layout> </appender> <root level="info"> <appender-ref ref="console" /> </root> </configuration>
小结
logback提供了MDCFilter,它可以根据指定的MDCKey从MDC取值,然后根据配置的value进行判断,然后执行onMatch或者onMismatch来决定是否打印日志。
以上就是logback使用MDCFilter日志过滤源码解读的详细内容,更多关于logback MDCFilter日志过滤的资料请关注脚本之家其它相关文章!