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