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.logging.log4j.core.appender.rewrite;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  
22  import org.apache.logging.log4j.Logger;
23  import org.apache.logging.log4j.core.Core;
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.config.plugins.Plugin;
26  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
27  import org.apache.logging.log4j.core.config.plugins.PluginElement;
28  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
29  import org.apache.logging.log4j.core.impl.Log4jLogEvent;
30  import org.apache.logging.log4j.core.util.KeyValuePair;
31  import org.apache.logging.log4j.message.MapMessage;
32  import org.apache.logging.log4j.message.Message;
33  import org.apache.logging.log4j.status.StatusLogger;
34  
35  /**
36   * This policy modifies events by replacing or possibly adding keys and values to the MapMessage.
37   */
38  @Plugin(name = "MapRewritePolicy", category = Core.CATEGORY_NAME, elementType = "rewritePolicy", printObject = true)
39  public final class MapRewritePolicy implements RewritePolicy {
40      
41      /**
42       * Allow subclasses access to the status logger without creating another instance.
43       */
44      protected static final Logger LOGGER = StatusLogger.getLogger();
45  
46      private final Map<String, Object> map;
47  
48      private final Mode mode;
49  
50      private MapRewritePolicy(final Map<String, Object> map, final Mode mode) {
51          this.map = map;
52          this.mode = mode;
53      }
54  
55      /**
56       * Rewrite the event.
57       * @param source a logging event that may be returned or
58       * used to create a new logging event.
59       * @return The LogEvent after rewriting.
60       */
61      @Override
62      public LogEvent rewrite(final LogEvent source) {
63          final Message msg = source.getMessage();
64          if (msg == null || !(msg instanceof MapMessage)) {
65              return source;
66          }
67  
68          @SuppressWarnings("unchecked")
69          final MapMessage<?, Object> mapMsg = (MapMessage<?, Object>) msg;
70          final Map<String, Object> newMap = new HashMap<>(mapMsg.getData());
71          switch (mode) {
72              case Add: {
73                  newMap.putAll(map);
74                  break;
75              }
76              default: {
77                  for (final Map.Entry<String, Object> entry : map.entrySet()) {
78                      if (newMap.containsKey(entry.getKey())) {
79                          newMap.put(entry.getKey(), entry.getValue());
80                      }
81                  }
82              }
83          }
84          final Message message = mapMsg.newInstance(newMap);
85          return new Log4jLogEvent.Builder(source).setMessage(message).build();
86      }
87  
88      /**
89       * An enumeration to identify whether keys not in the MapMessage should be added or whether only existing
90       * keys should be updated.
91       */
92      public enum Mode {
93          
94          /**
95           * Keys should be added.
96           */
97          Add,
98          
99          /**
100          * Keys should be updated.
101          */
102         Update
103     }
104 
105     @Override
106     public String toString() {
107         final StringBuilder sb = new StringBuilder();
108         sb.append("mode=").append(mode);
109         sb.append(" {");
110         boolean first = true;
111         for (final Map.Entry<String, Object> entry : map.entrySet()) {
112             if (!first) {
113                 sb.append(", ");
114             }
115             sb.append(entry.getKey()).append('=').append(entry.getValue());
116             first = false;
117         }
118         sb.append('}');
119         return sb.toString();
120     }
121 
122     /**
123      * The factory method to create the MapRewritePolicy.
124      * @param mode The string representation of the Mode.
125      * @param pairs key/value pairs for the new Map keys and values.
126      * @return The MapRewritePolicy.
127      */
128     @PluginFactory
129     public static MapRewritePolicy createPolicy(
130             @PluginAttribute("mode") final String mode,
131             @PluginElement("KeyValuePair") final KeyValuePair[] pairs) {
132         Mode op = mode == null ? op = Mode.Add : Mode.valueOf(mode);
133         if (pairs == null || pairs.length == 0) {
134             LOGGER.error("keys and values must be specified for the MapRewritePolicy");
135             return null;
136         }
137         final Map<String, Object> map = new HashMap<>();
138         for (final KeyValuePair pair : pairs) {
139             final String key = pair.getKey();
140             if (key == null) {
141                 LOGGER.error("A null key is not valid in MapRewritePolicy");
142                 continue;
143             }
144             final String value = pair.getValue();
145             if (value == null) {
146                 LOGGER.error("A null value for key " + key + " is not allowed in MapRewritePolicy");
147                 continue;
148             }
149             map.put(pair.getKey(), pair.getValue());
150         }
151         if (map.isEmpty()) {
152             LOGGER.error("MapRewritePolicy is not configured with any valid key value pairs");
153             return null;
154         }
155         return new MapRewritePolicy(map, op);
156     }
157 }