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.beans.PropertyDescriptor;
22 import java.beans.Introspector;
23
24 import org.apache.log4j.rewrite.RewritePolicy;
25 import org.apache.log4j.helpers.LogLog;
26 import org.apache.log4j.spi.LoggingEvent;
27
28 /***
29 * This policy rewrites events by evaluating any
30 * JavaBean properties on the message object and adding them
31 * to the event properties. If the message object has a
32 * message property, the value of that property will be
33 * used as the message for the rewritten event and will
34 * not be added to the event properties. Values from the
35 * JavaBean properties will replace any existing property
36 * with the same name.
37 *
38 * The combination of the RewriteAppender and this policy
39 * performs the same actions as the ReflectionFilter from log4j 1.3.
40 */
41 public class ReflectionRewritePolicy implements RewritePolicy {
42 /***
43 * {@inheritDoc}
44 */
45 public LoggingEvent rewrite(final LoggingEvent source) {
46 Object msg = source.getMessage();
47 if (!(msg instanceof String)) {
48 Object newMsg = msg;
49 Map rewriteProps = new HashMap(source.getProperties());
50
51 try {
52 PropertyDescriptor[] props = Introspector.getBeanInfo(
53 msg.getClass(), Object.class).getPropertyDescriptors();
54 if (props.length > 0) {
55 for (int i=0;i<props.length;i++) {
56 try {
57 Object propertyValue =
58 props[i].getReadMethod().invoke(msg,
59 (Object[]) null);
60 if ("message".equalsIgnoreCase(props[i].getName())) {
61 newMsg = propertyValue;
62 } else {
63 rewriteProps.put(props[i].getName(), propertyValue);
64 }
65 } catch (Exception e) {
66 LogLog.warn("Unable to evaluate property " +
67 props[i].getName(), e);
68 }
69 }
70 return new LoggingEvent(
71 source.getFQNOfLoggerClass(),
72 source.getLogger(),
73 source.getTimeStamp(),
74 source.getLevel(),
75 newMsg,
76 source.getThreadName(),
77 source.getThrowableInformation(),
78 source.getNDC(),
79 source.getLocationInformation(),
80 rewriteProps);
81 }
82 } catch (Exception e) {
83 LogLog.warn("Unable to get property descriptors", e);
84 }
85
86 }
87 return source;
88 }
89 }