1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.log4j.pattern;
18
19 import org.apache.logging.log4j.core.LogEvent;
20 import org.apache.logging.log4j.core.config.plugins.Plugin;
21 import org.apache.logging.log4j.core.pattern.ConverterKeys;
22 import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
23 import org.apache.logging.log4j.core.pattern.PatternConverter;
24 import org.apache.logging.log4j.util.TriConsumer;
25
26
27
28
29
30
31 @Plugin(name = "Log4j1MdcPatternConverter", category = PatternConverter.CATEGORY)
32 @ConverterKeys({ "properties" })
33 public final class Log4j1MdcPatternConverter extends LogEventPatternConverter {
34
35
36
37 private final String key;
38
39
40
41
42
43
44 private Log4j1MdcPatternConverter(final String[] options) {
45 super(options != null && options.length > 0 ? "Log4j1MDC{" + options[0] + '}' : "Log4j1MDC", "property");
46 if (options != null && options.length > 0) {
47 key = options[0];
48 } else {
49 key = null;
50 }
51 }
52
53
54
55
56
57
58
59 public static Log4j1MdcPatternConverter newInstance(final String[] options) {
60 return new Log4j1MdcPatternConverter(options);
61 }
62
63
64
65
66 @Override
67 public void format(final LogEvent event, final StringBuilder toAppendTo) {
68 if (key == null) {
69
70 toAppendTo.append('{');
71 event.getContextData().forEach(APPEND_EACH, toAppendTo);
72 toAppendTo.append('}');
73 } else {
74
75 final Object val = event.getContextData().getValue(key);
76 if (val != null) {
77 toAppendTo.append(val);
78 }
79 }
80 }
81
82 private static TriConsumer<String, Object, StringBuilder> APPEND_EACH = new TriConsumer<String, Object, StringBuilder>() {
83 @Override
84 public void accept(final String key, final Object value, final StringBuilder toAppendTo) {
85 toAppendTo.append('{').append(key).append(',').append(value).append('}');
86 }
87 };
88 }