001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.classic.turbo; 015 016import org.slf4j.MDC; 017import org.slf4j.Marker; 018 019import ch.qos.logback.classic.Level; 020import ch.qos.logback.classic.Logger; 021import ch.qos.logback.core.spi.FilterReply; 022 023/** 024 * This class allows output for a given MDC value. 025 * 026 * <p> 027 * When the given value is identified by this TurboFilter, the reply is based on 028 * the OnMatch option. The information is taken from the MDC. For this 029 * TurboFilter to work, one must set the key that will be used to access the 030 * information in the MDC. 031 * 032 * <p> 033 * To allow output for the value, set the OnMatch option to ACCEPT. To disable 034 * output for the given value, set the OnMatch option to DENY. 035 * 036 * <p> 037 * By default, values of the OnMatch and OnMisMatch options are set to NEUTRAL. 038 * 039 * 040 * @author Ceki Gülcü 041 * @author Sébastien Pennec 042 */ 043public class MDCFilter extends MatchingFilter { 044 045 String MDCKey; 046 String value; 047 048 @Override 049 public void start() { 050 int errorCount = 0; 051 if (value == null) { 052 addError("\'value\' parameter is mandatory. Cannot start."); 053 errorCount++; 054 } 055 if (MDCKey == null) { 056 addError("\'MDCKey\' parameter is mandatory. Cannot start."); 057 errorCount++; 058 } 059 060 if (errorCount == 0) 061 this.start = true; 062 } 063 064 @Override 065 public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { 066 067 if (!isStarted()) { 068 return FilterReply.NEUTRAL; 069 } 070 071 String value = MDC.get(MDCKey); 072 if (this.value.equals(value)) { 073 return onMatch; 074 } 075 return onMismatch; 076 } 077 078 public void setValue(String value) { 079 this.value = value; 080 } 081 082 public void setMDCKey(String MDCKey) { 083 this.MDCKey = MDCKey; 084 } 085 086}