1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.log4j.rewrite;
18
19 import java.util.Map;
20 import java.util.HashMap;
21 import java.util.Iterator;
22
23 import org.apache.log4j.rewrite.RewritePolicy;
24 import org.apache.log4j.spi.LoggingEvent;
25
26 /***
27 * This policy rewrites events where the message of the
28 * original event implementes java.util.Map.
29 * All other events are passed through unmodified.
30 * If the map contains a "message" entry, the value will be
31 * used as the message for the rewritten event. The rewritten
32 * event will have a property set that is the combination of the
33 * original property set and the other members of the message map.
34 * If both the original property set and the message map
35 * contain the same entry, the value from the message map
36 * will overwrite the original property set.
37 *
38 * The combination of the RewriteAppender and this policy
39 * performs the same actions as the MapFilter from log4j 1.3.
40 */
41 public class MapRewritePolicy implements RewritePolicy {
42 /***
43 * {@inheritDoc}
44 */
45 public LoggingEvent rewrite(final LoggingEvent source) {
46 Object msg = source.getMessage();
47 if (msg instanceof Map) {
48 Map props = new HashMap(source.getProperties());
49 Map eventProps = (Map) msg;
50
51
52
53
54
55 Object newMsg = eventProps.get("message");
56 if (newMsg == null) {
57 newMsg = msg;
58 }
59
60 for(Iterator iter = eventProps.entrySet().iterator();
61 iter.hasNext();
62 ) {
63 Map.Entry entry = (Map.Entry) iter.next();
64 if (!("message".equals(entry.getKey()))) {
65 props.put(entry.getKey(), entry.getValue());
66 }
67 }
68
69 return new LoggingEvent(
70 source.getFQNOfLoggerClass(),
71 source.getLogger(),
72 source.getTimeStamp(),
73 source.getLevel(),
74 newMsg,
75 source.getThreadName(),
76 source.getThrowableInformation(),
77 source.getNDC(),
78 source.getLocationInformation(),
79 props);
80 } else {
81 return source;
82 }
83
84 }
85 }