View Javadoc
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 format "k1=v1, k2=v2, ..."
66       */
67      private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap) {
68          StringBuilder buf = new StringBuilder();
69          boolean first = true;
70          for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) {
71              if (first) {
72                  first = false;
73              } else {
74                  buf.append(", ");
75              }
76              // format: key0=value0, key1=value1
77              buf.append(entry.getKey()).append('=').append(entry.getValue());
78          }
79          return buf.toString();
80      }
81  }