2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package org.apache.log4j.rewrite;
19 import java.beans.Introspector;
20 import java.beans.PropertyDescriptor;
21 import java.util.HashMap;
24 import org.apache.log4j.Logger;
25 import org.apache.log4j.helpers.LogLog;
26 import org.apache.log4j.spi.LoggingEvent;
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
38 * The combination of the RewriteAppender and this policy
39 * performs the same actions as the ReflectionFilter from log4j 1.3.
41 public class ReflectionRewritePolicy implements RewritePolicy {
45 public LoggingEvent rewrite(final LoggingEvent source) {
46 Object msg = source.getMessage();
47 if (!(msg instanceof String)) {
49 Map rewriteProps = new HashMap(source.getProperties());
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++) {
57 Object propertyValue =
58 props[i].getReadMethod().invoke(msg,
60 if ("message".equalsIgnoreCase(props[i].getName())) {
61 newMsg = propertyValue;
63 rewriteProps.put(props[i].getName(), propertyValue);
65 } catch (Exception e) {
66 LogLog.warn("Unable to evaluate property " +
67 props[i].getName(), e);
70 return new LoggingEvent(
71 source.getFQNOfLoggerClass(),
72 source.getLogger() != null ? source.getLogger(): Logger.getLogger(source.getLoggerName()),
73 source.getTimeStamp(),
76 source.getThreadName(),
77 source.getThrowableInformation(),
79 source.getLocationInformation(),
82 } catch (Exception e) {
83 LogLog.warn("Unable to get property descriptors", e);