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.sift;
15
16 import ch.qos.logback.classic.spi.ILoggingEvent;
17 import ch.qos.logback.core.sift.AbstractDiscriminator;
18 import ch.qos.logback.core.util.OptionHelper;
19
20 import java.util.Map;
21
22 /**
23 * MDCBasedDiscriminator essentially returns the value mapped to an MDC key. If
24 * the said value is null, then a default value is returned.
25 * <p/>
26 * <p>
27 * Both Key and the DefaultValue are user specified properties.
28 *
29 * @author Ceki Gülcü
30 */
31 public class MDCBasedDiscriminator extends AbstractDiscriminator<ILoggingEvent> {
32
33 private String key;
34 private String defaultValue;
35
36 /**
37 * Return the value associated with an MDC entry designated by the Key property.
38 * If that value is null, then return the value assigned to the DefaultValue
39 * property.
40 */
41 public String getDiscriminatingValue(ILoggingEvent event) {
42 // http://jira.qos.ch/browse/LBCLASSIC-213
43 Map<String, String> mdcMap = event.getMDCPropertyMap();
44 if (mdcMap == null) {
45 return defaultValue;
46 }
47 String mdcValue = mdcMap.get(key);
48 if (mdcValue == null) {
49 return defaultValue;
50 } else {
51 return mdcValue;
52 }
53 }
54
55 @Override
56 public void start() {
57 int errors = 0;
58 if (OptionHelper.isNullOrEmptyOrAllSpaces(key)) {
59 errors++;
60 addError("The \"Key\" property must be set");
61 }
62 if (OptionHelper.isNullOrEmptyOrAllSpaces(defaultValue)) {
63 errors++;
64 addError("The \"DefaultValue\" property must be set");
65 }
66 if (errors == 0) {
67 started = true;
68 }
69 }
70
71 public String getKey() {
72 return key;
73 }
74
75 public void setKey(String key) {
76 this.key = key;
77 }
78
79 /**
80 * @return
81 * @see #setDefaultValue(String)
82 */
83 public String getDefaultValue() {
84 return defaultValue;
85 }
86
87 /**
88 * The default MDC value in case the MDC is not set for {@link #setKey(String)
89 * mdcKey}.
90 * <p/>
91 * <p>
92 * For example, if {@link #setKey(String) Key} is set to the value "someKey",
93 * and the MDC is not set for "someKey", then this appender will use the default
94 * value, which you can set with the help of this method.
95 *
96 * @param defaultValue
97 */
98 public void setDefaultValue(String defaultValue) {
99 this.defaultValue = defaultValue;
100 }
101 }