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.beans.Introspector;
20 import java.beans.PropertyDescriptor;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.apache.log4j.Logger;
25 import org.apache.log4j.helpers.LogLog;
26 import org.apache.log4j.spi.LoggingEvent;
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 (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() != 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 }