1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.pattern;
19
20 import org.apache.log4j.spi.LoggingEvent;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
26 import java.lang.reflect.*;
27 import java.util.Iterator;
28 import java.util.Set;
29 import org.apache.log4j.helpers.*;
30
31
32 /***
33 * Able to handle the contents of the LoggingEvent's Property bundle and either
34 * output the entire contents of the properties in a similar format to the
35 * java.util.Hashtable.toString(), or to output the value of a specific key
36 * within the property bundle
37 * when this pattern converter has the option set.
38 *
39 * @author Paul Smith
40 * @author Ceki Gülcü
41 */
42 public final class PropertiesPatternConverter
43 extends LoggingEventPatternConverter {
44 /***
45 * Name of property to output.
46 */
47 private final String option;
48
49 /***
50 * Private constructor.
51 * @param options options, may be null.
52 */
53 private PropertiesPatternConverter(
54 final String[] options) {
55 super(
56 ((options != null) && (options.length > 0))
57 ? ("Property{" + options[0] + "}") : "Properties", "property");
58
59 if ((options != null) && (options.length > 0)) {
60 option = options[0];
61 } else {
62 option = null;
63 }
64 }
65
66 /***
67 * Obtains an instance of PropertiesPatternConverter.
68 * @param options options, may be null or first element contains name of property to format.
69 * @return instance of PropertiesPatternConverter.
70 */
71 public static PropertiesPatternConverter newInstance(
72 final String[] options) {
73 return new PropertiesPatternConverter(options);
74 }
75
76 /***
77 * {@inheritDoc}
78 */
79 public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
80
81
82 if (option == null) {
83 toAppendTo.append("{");
84
85 try {
86 Set keySet = MDCKeySetExtractor.INSTANCE.getPropertyKeySet(event);
87 if (keySet != null) {
88 for (Iterator i = keySet.iterator(); i.hasNext();) {
89 Object item = i.next();
90 Object val = event.getMDC(item.toString());
91 toAppendTo.append("{").append(item).append(",").append(val).append(
92 "}");
93 }
94 }
95 } catch(Exception ex) {
96 LogLog.error("Unexpected exception while extracting MDC keys", ex);
97 }
98
99 toAppendTo.append("}");
100 } else {
101
102 Object val = event.getMDC(option);
103
104 if (val != null) {
105 toAppendTo.append(val);
106 }
107 }
108 }
109 }