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, the reply is based on
28 * the OnMatch option. The information is taken from the MDC. For this
29 * TurboFilter to work, one must set the key that will be used to access the
30 * information in the MDC.
31 *
32 * <p>
33 * To allow output for the value, set the OnMatch option to ACCEPT. To disable
34 * output for the given value, set the OnMatch option to DENY.
35 *
36 * <p>
37 * By default, values of the OnMatch and OnMisMatch options are set to NEUTRAL.
38 *
39 *
40 * @author Ceki Gülcü
41 * @author Sébastien Pennec
42 */
43 public class MDCFilter extends MatchingFilter {
44
45 String MDCKey;
46 String value;
47
48 @Override
49 public void start() {
50 int errorCount = 0;
51 if (value == null) {
52 addError("\'value\' parameter is mandatory. Cannot start.");
53 errorCount++;
54 }
55 if (MDCKey == null) {
56 addError("\'MDCKey\' parameter is mandatory. Cannot start.");
57 errorCount++;
58 }
59
60 if (errorCount == 0)
61 this.start = true;
62 }
63
64 @Override
65 public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
66
67 if (!isStarted()) {
68 return FilterReply.NEUTRAL;
69 }
70
71 String value = MDC.get(MDCKey);
72 if (this.value.equals(value)) {
73 return onMatch;
74 }
75 return onMismatch;
76 }
77
78 public void setValue(String value) {
79 this.value = value;
80 }
81
82 public void setMDCKey(String MDCKey) {
83 this.MDCKey = MDCKey;
84 }
85
86 }