View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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.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        // if no key is specified, return all the
52        // values present in the MDC, separated with a single space.
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          //format: {testeKey=testValue, testKey2=testValue2}
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  }