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 org.apache.log4j.Logger;
20 import org.apache.log4j.helpers.LogLog;
21 import org.apache.log4j.spi.LoggingEvent;
22
23 import java.beans.Introspector;
24 import java.beans.PropertyDescriptor;
25 import java.util.HashMap;
26 import java.util.Map;
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class ReflectionRewritePolicy implements RewritePolicy {
42
43
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 (PropertyDescriptor prop : props) {
56 try {
57 Object propertyValue =
58 prop.getReadMethod().invoke(msg,
59 (Object[]) null);
60 if ("message".equalsIgnoreCase(prop.getName())) {
61 newMsg = propertyValue;
62 } else {
63 rewriteProps.put(prop.getName(), propertyValue);
64 }
65 } catch (Exception e) {
66 LogLog.warn("Unable to evaluate property " +
67 prop.getName(), e);
68 }
69 }
70 return new LoggingEvent(
71 source.getFQNOfLoggerClass(),
72 source.getLogger() != null ? source.getLogger() : Logger.getLogger(source.getLoggerName()),
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 }