1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.pattern;
15
16 import java.util.Iterator;
17 import java.util.Map;
18 import java.util.Set;
19
20 import ch.qos.logback.classic.spi.ILoggingEvent;
21
22 public class MDCConverter extends ClassicConverter {
23
24 String key;
25 private static final String EMPTY_STRING = "";
26
27 public MDCConverter() {
28 }
29
30 @Override
31 public void start() {
32 key = getFirstOption();
33 super.start();
34 }
35
36 @Override
37 public void stop() {
38 key = null;
39 super.stop();
40 }
41
42 @Override
43 public String convert(ILoggingEvent event) {
44 Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
45
46 if (mdcPropertyMap == null) {
47 return EMPTY_STRING;
48 }
49
50 if (key == null) {
51
52
53 StringBuilder buf = new StringBuilder();
54 Set<String> keys = mdcPropertyMap.keySet();
55 Iterator it = keys.iterator();
56 String tmpKey;
57 String tmpValue;
58 while (it.hasNext()) {
59 tmpKey = (String)it.next();
60 tmpValue = (String)mdcPropertyMap.get(tmpKey);
61
62 buf.append(tmpKey).append('=').append(tmpValue);
63 if (it.hasNext()) {
64 buf.append(", ");
65 }
66 }
67 return buf.toString();
68 }
69
70 String value = event.getMDCPropertyMap().get(key);
71 if (value != null) {
72 return value;
73 } else {
74 return EMPTY_STRING;
75 }
76 }
77 }