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.Filter;
27  import org.apache.logging.log4j.core.LogEvent;
28  import org.apache.logging.log4j.core.Logger;
29  import org.apache.logging.log4j.core.config.Node;
30  import org.apache.logging.log4j.core.config.plugins.Plugin;
31  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
32  import org.apache.logging.log4j.core.config.plugins.PluginElement;
33  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
34  import org.apache.logging.log4j.core.util.KeyValuePair;
35  import org.apache.logging.log4j.message.Message;
36  import org.apache.logging.log4j.message.StructuredDataMessage;
37  import org.apache.logging.log4j.util.IndexedReadOnlyStringMap;
38  import org.apache.logging.log4j.util.PerformanceSensitive;
39  import org.apache.logging.log4j.util.StringBuilders;
40  
41  /**
42   * Filter based on data in a StructuredDataMessage.
43   */
44  @Plugin(name = "StructuredDataFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
45  @PerformanceSensitive("allocation")
46  public final class StructuredDataFilter extends MapFilter {
47  
48      private static final int MAX_BUFFER_SIZE = 2048;
49      private static ThreadLocal<StringBuilder> threadLocalStringBuilder = new ThreadLocal<>();
50  
51      private StructuredDataFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
52                                   final Result onMismatch) {
53          super(map, oper, onMatch, onMismatch);
54      }
55  
56      @Override
57      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
58                           final Throwable t) {
59          if (msg instanceof StructuredDataMessage) {
60              return filter((StructuredDataMessage) msg);
61          }
62          return Result.NEUTRAL;
63      }
64  
65      @Override
66      public Result filter(final LogEvent event) {
67          final Message msg = event.getMessage();
68          if (msg instanceof StructuredDataMessage) {
69              return filter((StructuredDataMessage) msg);
70          }
71          return super.filter(event);
72      }
73  
74      protected Result filter(final StructuredDataMessage message) {
75          boolean match = false;
76          final IndexedReadOnlyStringMap map = getStringMap();
77          for (int i = 0; i < map.size(); i++) {
78              final StringBuilder toMatch = getValue(message, map.getKeyAt(i));
79              if (toMatch != null) {
80                  match = listContainsValue((List<String>) map.getValueAt(i), toMatch);
81              } else {
82                  match = false;
83              }
84              if ((!isAnd() && match) || (isAnd() && !match)) {
85                  break;
86              }
87          }
88          return match ? onMatch : onMismatch;
89      }
90  
91      private StringBuilder getValue(final StructuredDataMessage data, final String key) {
92          final StringBuilder sb = getStringBuilder();
93          if (key.equalsIgnoreCase("id")) {
94              data.getId().formatTo(sb);
95              return sb;
96          } else if (key.equalsIgnoreCase("id.name")) {
97              return appendOrNull(data.getId().getName(), sb);
98          } else if (key.equalsIgnoreCase("type")) {
99              return appendOrNull(data.getType(), sb);
100         } else if (key.equalsIgnoreCase("message")) {
101             data.formatTo(sb);
102             return sb;
103         } else {
104             return appendOrNull(data.get(key), sb);
105         }
106     }
107 
108     private StringBuilder getStringBuilder() {
109         StringBuilder result = threadLocalStringBuilder.get();
110         if (result == null) {
111             result = new StringBuilder();
112             threadLocalStringBuilder.set(result);
113         }
114         if (result.length() > MAX_BUFFER_SIZE) {
115             result.setLength(MAX_BUFFER_SIZE);
116             result.trimToSize();
117         }
118         result.setLength(0);
119         return result;
120     }
121 
122     private StringBuilder appendOrNull(final String value, final StringBuilder sb) {
123         if (value == null) {
124             return null;
125         }
126         sb.append(value);
127         return sb;
128     }
129 
130     private boolean listContainsValue(final List<String> candidates, final StringBuilder toMatch) {
131         if (toMatch == null) {
132             for (int i = 0; i < candidates.size(); i++) {
133                 final String candidate = candidates.get(i);
134                 if (candidate == null) {
135                     return true;
136                 }
137             }
138         } else {
139             for (int i = 0; i < candidates.size(); i++) {
140                 final String candidate = candidates.get(i);
141                 if (candidate == null) {
142                     return false;
143                 }
144                 if (StringBuilders.equals(candidate, 0, candidate.length(), toMatch, 0, toMatch.length())) {
145                     return true;
146                 }
147             }
148         }
149         return false;
150     }
151 
152     /**
153      * Create the StructuredDataFilter.
154      * @param pairs Key and value pairs.
155      * @param oper The operator to perform. If not "or" the operation will be an "and".
156      * @param match The action to perform on a match.
157      * @param mismatch The action to perform on a mismatch.
158      * @return The StructuredDataFilter.
159      */
160     @PluginFactory
161     public static StructuredDataFilter createFilter(
162             @PluginElement("Pairs") final KeyValuePair[] pairs,
163             @PluginAttribute("operator") final String oper,
164             @PluginAttribute("onMatch") final Result match,
165             @PluginAttribute("onMismatch") final Result mismatch) {
166         if (pairs == null || pairs.length == 0) {
167             LOGGER.error("keys and values must be specified for the StructuredDataFilter");
168             return null;
169         }
170         final Map<String, List<String>> map = new HashMap<>();
171         for (final KeyValuePair pair : pairs) {
172             final String key = pair.getKey();
173             if (key == null) {
174                 LOGGER.error("A null key is not valid in MapFilter");
175                 continue;
176             }
177             final String value = pair.getValue();
178             if (value == null) {
179                 LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
180                 continue;
181             }
182             List<String> list = map.get(pair.getKey());
183             if (list != null) {
184                 list.add(value);
185             } else {
186                 list = new ArrayList<>();
187                 list.add(value);
188                 map.put(pair.getKey(), list);
189             }
190         }
191         if (map.isEmpty()) {
192             LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
193             return null;
194         }
195         final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
196         return new StructuredDataFilter(map, isAnd, match, mismatch);
197     }
198 }