1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.pattern;
15
16 import ch.qos.logback.classic.spi.ILoggingEvent;
17
18 import java.util.Map;
19
20 import static ch.qos.logback.core.util.OptionHelper.extractDefaultReplacement;
21
22 public class MDCConverter extends ClassicConverter {
23
24 private String key;
25 private String defaultValue = "";
26
27 @Override
28 public void start() {
29 String[] keyInfo = extractDefaultReplacement(getFirstOption());
30 key = keyInfo[0];
31 if (keyInfo[1] != null) {
32 defaultValue = keyInfo[1];
33 }
34 super.start();
35 }
36
37 @Override
38 public void stop() {
39 key = null;
40 super.stop();
41 }
42
43 @Override
44 public String convert(ILoggingEvent event) {
45 Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
46
47 if (mdcPropertyMap == null) {
48 return defaultValue;
49 }
50
51 if (key == null) {
52 return outputMDCForAllKeys(mdcPropertyMap);
53 } else {
54
55 String value = mdcPropertyMap.get(key);
56 if (value != null) {
57 return value;
58 } else {
59 return defaultValue;
60 }
61 }
62 }
63
64
65
66
67
68 private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap) {
69 StringBuilder buf = new StringBuilder();
70 boolean first = true;
71 for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) {
72 if (first) {
73 first = false;
74 } else {
75 buf.append(", ");
76 }
77
78 buf.append(entry.getKey()).append('=').append(entry.getValue());
79 }
80 return buf.toString();
81 }
82
83
84
85
86
87
88 public String getKey() {
89 return key;
90 }
91
92 }