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.MapMessage;
26  import org.apache.logging.log4j.message.Message;
27  import org.apache.logging.log4j.message.SimpleMessage;
28  import org.apache.logging.log4j.util.SortedArrayStringMap;
29  
30  import java.util.HashMap;
31  import java.util.Map;
32  
33  /**
34   * This policy rewrites events where the message of the
35   * original event implements java.util.Map.
36   * All other events are passed through unmodified.
37   * If the map contains a "message" entry, the value will be
38   * used as the message for the rewritten event.  The rewritten
39   * event will have a property set that is the combination of the
40   * original property set and the other members of the message map.
41   * If both the original property set and the message map
42   * contain the same entry, the value from the message map
43   * will overwrite the original property set.
44   * <p>
45   * The combination of the RewriteAppender and this policy
46   * performs the same actions as the MapFilter from log4j 1.3.
47   * </p>
48   */
49  public class MapRewritePolicy implements RewritePolicy {
50      /**
51       * {@inheritDoc}
52       */
53      @Override
54      public LoggingEvent rewrite(final LoggingEvent source) {
55          Object msg = source.getMessage();
56          if (msg instanceof MapMessage || msg instanceof Map) {
57              Map<String, String> props = source.getProperties() != null ? new HashMap<>(source.getProperties())
58                      : new HashMap<>();
59              @SuppressWarnings("unchecked")
60              Map<String, Object> eventProps = msg instanceof Map ? (Map) msg : ((MapMessage) msg).getData();
61              //
62              //   if the map sent in the logging request
63              //      has "message" entry, use that as the message body
64              //      otherwise, use the entire map.
65              //
66              Message newMessage = null;
67              Object newMsg = eventProps.get("message");
68              if (newMsg != null) {
69                  newMessage = new SimpleMessage(newMsg.toString());
70                  for (Map.Entry<String, Object> entry : eventProps.entrySet()) {
71                      if (!("message".equals(entry.getKey()))) {
72                          props.put(entry.getKey(), entry.getValue().toString());
73                      }
74                  }
75              } else {
76                  return source;
77              }
78  
79              LogEvent event;
80              if (source instanceof LogEventAdapter) {
81                  event = new Log4jLogEvent.Builder(((LogEventAdapter) source).getEvent())
82                          .setMessage(newMessage)
83                          .setContextData(new SortedArrayStringMap(props))
84                          .build();
85              } else {
86                  LocationInfo info = source.getLocationInformation();
87                  StackTraceElement element = new StackTraceElement(info.getClassName(), info.getMethodName(),
88                          info.getFileName(), Integer.parseInt(info.getLineNumber()));
89                  Thread thread = getThread(source.getThreadName());
90                  long threadId = thread != null ? thread.getId() : 0;
91                  int threadPriority = thread != null ? thread.getPriority() : 0;
92                  event = Log4jLogEvent.newBuilder()
93                          .setContextData(new SortedArrayStringMap(props))
94                          .setLevel(OptionConverter.convertLevel(source.getLevel()))
95                          .setLoggerFqcn(source.getFQNOfLoggerClass())
96                          .setMarker(null)
97                          .setMessage(newMessage)
98                          .setSource(element)
99                          .setLoggerName(source.getLoggerName())
100                         .setThreadName(source.getThreadName())
101                         .setThreadId(threadId)
102                         .setThreadPriority(threadPriority)
103                         .setThrown(source.getThrowableInformation().getThrowable())
104                         .setTimeMillis(source.getTimeStamp())
105                         .setNanoTime(0)
106                         .setThrownProxy(null)
107                         .build();
108             }
109             return new LogEventAdapter(event);
110         }
111         return source;
112 
113     }
114 
115     private Thread getThread(String name) {
116         for (Thread thread : Thread.getAllStackTraces().keySet()) {
117             if (thread.getName().equals(name)) {
118                 return thread;
119             }
120         }
121         return null;
122     }
123 }