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