1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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 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       * if no key is specified, return all the values present in the MDC, in the
66       * format "k1=v1, k2=v2, ..."
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              // format: key0=value0, key1=value1
78              buf.append(entry.getKey()).append('=').append(entry.getValue());
79          }
80          return buf.toString();
81      }
82  
83      /**
84       * PrefixCompositeConverter needs the key
85       * 
86       * @return
87       */
88      public String getKey() {
89          return key;
90      }
91  
92  }