View Javadoc
1   /*
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
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
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.
16   */
17  package org.apache.log4j.rewrite;
18  
19  import org.apache.log4j.bridge.LogEventAdapter;
20  import org.apache.log4j.helpers.OptionConverter;
21  import org.apache.log4j.spi.LocationInfo;
22  import org.apache.log4j.spi.LoggingEvent;
23  import org.apache.logging.log4j.core.LogEvent;
24  import org.apache.logging.log4j.core.impl.Log4jLogEvent;
25  import org.apache.logging.log4j.message.SimpleMessage;
26  import org.apache.logging.log4j.util.SortedArrayStringMap;
27  
28  import java.util.Collections;
29  import java.util.HashMap;
30  import java.util.Map;
31  import java.util.StringTokenizer;
32  
33  /**
34   * This policy rewrites events by adding
35   * a user-specified list of properties to the event.
36   * Existing properties are not modified.
37   * <p>
38   * The combination of the RewriteAppender and this policy
39   * performs the same actions as the PropertyFilter from log4j 1.3.
40   */
41  
42  public class PropertyRewritePolicy implements RewritePolicy {
43      private Map<String, String> properties = Collections.EMPTY_MAP;
44  
45      public PropertyRewritePolicy() {
46      }
47  
48      /**
49       * Set a string representing the property name/value pairs.
50       * <p>
51       * Form: propname1=propvalue1,propname2=propvalue2
52       *
53       * @param props The properties.
54       */
55      public void setProperties(String props) {
56          Map hashTable = new HashMap();
57          StringTokenizer pairs = new StringTokenizer(props, ",");
58          while (pairs.hasMoreTokens()) {
59              StringTokenizer entry = new StringTokenizer(pairs.nextToken(), "=");
60              hashTable.put(entry.nextElement().toString().trim(), entry.nextElement().toString().trim());
61          }
62          synchronized (this) {
63              properties = hashTable;
64          }
65      }
66  
67      /**
68       * {@inheritDoc}
69       */
70      public LoggingEvent rewrite(final LoggingEvent source) {
71          if (!properties.isEmpty()) {
72              Map<String, String> rewriteProps = source.getProperties() != null ? new HashMap<>(source.getProperties())
73                      : new HashMap<>();
74              for (Map.Entry<String, String> entry : properties.entrySet()) {
75                  if (!rewriteProps.containsKey(entry.getKey())) {
76                      rewriteProps.put(entry.getKey(), entry.getValue());
77                  }
78              }
79              LogEvent event;
80              if (source instanceof LogEventAdapter) {
81                  event = new Log4jLogEvent.Builder(((LogEventAdapter) source).getEvent())
82                          .setContextData(new SortedArrayStringMap(rewriteProps))
83                          .build();
84              } else {
85                  LocationInfo info = source.getLocationInformation();
86                  StackTraceElement element = new StackTraceElement(info.getClassName(), info.getMethodName(),
87                          info.getFileName(), Integer.parseInt(info.getLineNumber()));
88                  Thread thread = getThread(source.getThreadName());
89                  long threadId = thread != null ? thread.getId() : 0;
90                  int threadPriority = thread != null ? thread.getPriority() : 0;
91                  event = Log4jLogEvent.newBuilder()
92                          .setContextData(new SortedArrayStringMap(rewriteProps))
93                          .setLevel(OptionConverter.convertLevel(source.getLevel()))
94                          .setLoggerFqcn(source.getFQNOfLoggerClass())
95                          .setMarker(null)
96                          .setMessage(new SimpleMessage(source.getRenderedMessage()))
97                          .setSource(element)
98                          .setLoggerName(source.getLoggerName())
99                          .setThreadName(source.getThreadName())
100                         .setThreadId(threadId)
101                         .setThreadPriority(threadPriority)
102                         .setThrown(source.getThrowableInformation().getThrowable())
103                         .setTimeMillis(source.getTimeStamp())
104                         .setNanoTime(0)
105                         .setThrownProxy(null)
106                         .build();
107             }
108             return new LogEventAdapter(event);
109         }
110         return source;
111     }
112 
113     private Thread getThread(String name) {
114         for (Thread thread : Thread.getAllStackTraces().keySet()) {
115             if (thread.getName().equals(name)) {
116                 return thread;
117             }
118         }
119         return null;
120     }
121 }