View Javadoc
1   package ch.qos.logback.classic.pattern;
2   
3   import java.util.List;
4   
5   import org.slf4j.event.KeyValuePair;
6   
7   import ch.qos.logback.classic.spi.ILoggingEvent;
8   import ch.qos.logback.core.CoreConstants;
9   
10  /**
11   * Convert the contents of {@link KeyValuePair} list to a String.
12   * 
13   * Assuming the list contains the list {k1, v1}, {k2, v2}, the String output
14   * will be "k1=v1 k2=v2", without the quotes.
15   *
16   * 
17   * @since 1.3.0
18   * @author Ceki Gülcü
19   *
20   */
21  public class KeyValuePairConverter extends ClassicConverter {
22  
23      static final String DOUBLE_OPTION_STR = "DOUBLE";
24      static final String SINGLE_OPTION_STR = "SINGLE";
25      static final String NONE_OPTION_STR = "NONE";
26  
27      enum ValueQuoteSpecification {
28          NONE, SINGLE, DOUBLE;
29  
30          Character asChar() {
31              switch (this) {
32              case NONE:
33                  return null;
34              case DOUBLE:
35                  return '"';
36              case SINGLE:
37                  return '\'';
38              default:
39                  throw new IllegalStateException();
40              }
41          }
42      }
43  
44      ValueQuoteSpecification valueQuoteSpec = ValueQuoteSpecification.DOUBLE;
45  
46      public void start() {
47          String optStr = getFirstOption();
48          valueQuoteSpec = optionStrToSpec(optStr);
49          super.start();
50      }
51  
52      private ValueQuoteSpecification optionStrToSpec(String optStr) {
53          if (optStr == null)
54              return ValueQuoteSpecification.DOUBLE;
55          if (DOUBLE_OPTION_STR.equalsIgnoreCase(optStr))
56              return ValueQuoteSpecification.DOUBLE;
57          if (SINGLE_OPTION_STR.equalsIgnoreCase(optStr))
58              return ValueQuoteSpecification.SINGLE;
59          if (NONE_OPTION_STR.equalsIgnoreCase(optStr))
60              return ValueQuoteSpecification.NONE;
61          return ValueQuoteSpecification.DOUBLE;
62      }
63  
64      @Override
65      public String convert(ILoggingEvent event) {
66  
67          List<KeyValuePair> kvpList = event.getKeyValuePairs();
68          if (kvpList == null || kvpList.isEmpty()) {
69              return CoreConstants.EMPTY_STRING;
70          }
71  
72          StringBuilder sb = new StringBuilder();
73          for (int i = 0; i < kvpList.size(); i++) {
74              KeyValuePair kvp = kvpList.get(i);
75              if (i != 0)
76                  sb.append(' ');
77              sb.append(String.valueOf(kvp.key));
78              sb.append('=');
79              Character quoteChar = valueQuoteSpec.asChar();
80              if (quoteChar != null)
81                  sb.append(quoteChar);
82              sb.append(String.valueOf(kvp.value));
83              if (quoteChar != null)
84                  sb.append(quoteChar);
85          }
86  
87          return sb.toString();
88      }
89  
90  }