1
2
3
4
5
6
7
8
9
10 package ch.qos.logback.classic.sift;
11
12 import org.slf4j.MDC;
13
14 import ch.qos.logback.classic.spi.LoggingEvent;
15 import ch.qos.logback.core.sift.Discriminator;
16 import ch.qos.logback.core.spi.ContextAwareBase;
17 import ch.qos.logback.core.util.OptionHelper;
18
19
20
21
22
23
24
25
26
27
28 public class MDCBasedDiscriminator extends ContextAwareBase implements
29 Discriminator<LoggingEvent> {
30
31 private String key;
32 private String defaultValue;
33 private boolean started = false;
34
35 public MDCBasedDiscriminator() {
36 }
37
38
39
40
41
42
43 public String getDiscriminatingValue(LoggingEvent event) {
44 String mdcValue = MDC.get(key);
45 if (mdcValue == null) {
46 return defaultValue;
47 } else {
48 return mdcValue;
49 }
50 }
51
52 public boolean isStarted() {
53 return started;
54 }
55
56 public void start() {
57 int errors = 0;
58 if (OptionHelper.isEmpty(key)) {
59 errors++;
60 addError("The \"Key\" property must be set");
61 }
62 if (OptionHelper.isEmpty(defaultValue)) {
63 errors++;
64 addError("The \"DefaultValue\" property must be set");
65 }
66 if (errors == 0) {
67 started = true;
68 }
69 }
70
71 public void stop() {
72 started = false;
73 }
74
75 public String getKey() {
76 return key;
77 }
78
79 public void setKey(String key) {
80 this.key = key;
81 }
82
83
84
85
86
87 public String getDefaultValue() {
88 return defaultValue;
89 }
90
91
92
93
94
95
96
97
98
99
100
101 public void setDefaultValue(String defaultValue) {
102 this.defaultValue = defaultValue;
103 }
104 }