View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.turbo;
15  
16  import org.slf4j.MDC;
17  import org.slf4j.Marker;
18  
19  import ch.qos.logback.classic.Level;
20  import ch.qos.logback.classic.Logger;
21  import ch.qos.logback.core.spi.FilterReply;
22  
23  /**
24   * This class allows output for a given MDC value.
25   * 
26   * <p>
27   * When the given value is identified by this TurboFilter, 
28   * the reply is based on the OnMatch option.
29   * The information is taken from the MDC. For this TurboFilter to work,
30   * one must set the key that will be used to 
31   * access the information in the MDC.
32   * 
33   * <p>
34   * To allow output for the value, set the OnMatch option
35   * to ACCEPT. To disable output for the given value, set
36   * the OnMatch option to DENY.
37   * 
38   * <p>
39   * By default, values of the OnMatch and OnMisMatch
40   * options are set to NEUTRAL.
41   * 
42   *
43   * @author Ceki G&uuml;lc&uuml;
44   * @author S&eacute;bastien Pennec
45   */
46  public class MDCFilter extends MatchingFilter {
47  
48      String MDCKey;
49      String value;
50  
51      
52      @Override
53      public void start() {
54          int errorCount = 0;
55          if(value == null) {
56              addError("\'value\' parameter is mandatory. Cannot start.");
57              errorCount++;
58          }
59          if(MDCKey == null) {
60              addError("\'MDCKey\' parameter is mandatory. Cannot start.");
61              errorCount++;
62          }
63          
64          if(errorCount == 0)
65              this.start = true;
66      }
67      @Override
68      public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
69          
70          if (!isStarted()) {
71              return FilterReply.NEUTRAL;
72          }
73  
74          String value = MDC.get(MDCKey);
75          if (this.value.equals(value)) {
76              return onMatch;
77          }
78          return onMismatch;
79      }
80  
81      public void setValue(String value) {
82          this.value = value;
83      }
84  
85      public void setMDCKey(String MDCKey) {
86          this.MDCKey = MDCKey;
87      }
88  
89  }