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.filter;
18  
19  import java.util.ArrayList;
20  import java.util.HashMap;
21  import java.util.List;
22  import java.util.Map;
23  
24  import org.apache.logging.log4j.Level;
25  import org.apache.logging.log4j.Marker;
26  import org.apache.logging.log4j.core.LogEvent;
27  import org.apache.logging.log4j.core.Logger;
28  import org.apache.logging.log4j.core.config.plugins.Plugin;
29  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
30  import org.apache.logging.log4j.core.config.plugins.PluginElement;
31  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
32  import org.apache.logging.log4j.core.helpers.KeyValuePair;
33  import org.apache.logging.log4j.message.MapMessage;
34  import org.apache.logging.log4j.message.Message;
35  
36  /**
37   * A Filter that operates on a Map.
38   */
39  @Plugin(name = "MapFilter", category = "Core", elementType = "filter", printObject = true)
40  public class MapFilter extends AbstractFilter {
41      private final Map<String, List<String>> map;
42  
43      private final boolean isAnd;
44  
45      protected MapFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
46                          final Result onMismatch) {
47          super(onMatch, onMismatch);
48          if (map == null) {
49              throw new NullPointerException("key cannot be null");
50          }
51          this.isAnd = oper;
52          this.map = map;
53      }
54  
55      @Override
56      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
57                           final Throwable t) {
58          if (msg instanceof MapMessage) {
59              return filter(((MapMessage) msg).getData()) ? onMatch : onMismatch;
60          }
61          return Result.NEUTRAL;
62      }
63  
64      @Override
65      public Result filter(final LogEvent event) {
66          final Message msg = event.getMessage();
67          if (msg instanceof MapMessage) {
68              return filter(((MapMessage) msg).getData()) ? onMatch : onMismatch;
69          }
70          return Result.NEUTRAL;
71      }
72  
73      protected boolean filter(final Map<String, String> data) {
74          boolean match = false;
75          for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
76              final String toMatch = data.get(entry.getKey());
77              if (toMatch != null) {
78                  match = entry.getValue().contains(toMatch);
79              } else {
80                  match = false;
81              }
82              if ((!isAnd && match) || (isAnd && !match)) {
83                  break;
84              }
85          }
86          return match;
87      }
88  
89      @Override
90      public String toString() {
91          final StringBuilder sb = new StringBuilder();
92          sb.append("isAnd=").append(isAnd);
93          if (map.size() > 0) {
94              sb.append(", {");
95              boolean first = true;
96              for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
97                  if (!first) {
98                      sb.append(", ");
99                  }
100                 first = false;
101                 final List<String> list = entry.getValue();
102                 final String value = list.size() > 1 ? list.get(0) : list.toString();
103                 sb.append(entry.getKey()).append("=").append(value);
104             }
105             sb.append("}");
106         }
107         return sb.toString();
108     }
109 
110     protected boolean isAnd() {
111         return isAnd;
112     }
113 
114     protected Map<String, List<String>> getMap() {
115         return map;
116     }
117 
118     @PluginFactory
119     public static MapFilter createFilter(
120             @PluginElement("Pairs") final KeyValuePair[] pairs,
121             @PluginAttribute("operator") final String oper,
122             @PluginAttribute("onMatch") final String match,
123             @PluginAttribute("onMismatch") final String mismatch) {
124         if (pairs == null || pairs.length == 0) {
125             LOGGER.error("keys and values must be specified for the MapFilter");
126             return null;
127         }
128         final Map<String, List<String>> map = new HashMap<String, List<String>>();
129         for (final KeyValuePair pair : pairs) {
130             final String key = pair.getKey();
131             if (key == null) {
132                 LOGGER.error("A null key is not valid in MapFilter");
133                 continue;
134             }
135             final String value = pair.getValue();
136             if (value == null) {
137                 LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
138                 continue;
139             }
140             List<String> list = map.get(pair.getKey());
141             if (list != null) {
142                 list.add(value);
143             } else {
144                 list = new ArrayList<String>();
145                 list.add(value);
146                 map.put(pair.getKey(), list);
147             }
148         }
149         if (map.size() == 0) {
150             LOGGER.error("MapFilter is not configured with any valid key value pairs");
151             return null;
152         }
153         final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
154         final Result onMatch = Result.toResult(match);
155         final Result onMismatch = Result.toResult(mismatch);
156         return new MapFilter(map, isAnd, onMatch, onMismatch);
157     }
158 }