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.Message;
34  import org.apache.logging.log4j.message.StructuredDataMessage;
35  
36  /**
37   * Filter based on data in a StructuredDataMessage.
38   */
39  @Plugin(name = "StructuredDataFilter", category = "Core", elementType = "filter", printObject = true)
40  public final class StructuredDataFilter extends MapFilter {
41  
42      private StructuredDataFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
43                                   final Result onMismatch) {
44          super(map, oper, onMatch, onMismatch);
45      }
46  
47      @Override
48      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
49                           final Throwable t) {
50          if (msg instanceof StructuredDataMessage) {
51              return filter((StructuredDataMessage) msg);
52          }
53          return Result.NEUTRAL;
54      }
55  
56      @Override
57      public Result filter(final LogEvent event) {
58          final Message msg = event.getMessage();
59          if (msg instanceof StructuredDataMessage) {
60              return filter((StructuredDataMessage) msg);
61          }
62          return super.filter(event);
63      }
64  
65      protected Result filter(final StructuredDataMessage message) {
66          boolean match = false;
67          for (final Map.Entry<String, List<String>> entry : getMap().entrySet()) {
68              final String toMatch = getValue(message, entry.getKey());
69              if (toMatch != null) {
70                  match = entry.getValue().contains(toMatch);
71              } else {
72                  match = false;
73              }
74              if ((!isAnd() && match) || (isAnd() && !match)) {
75                  break;
76              }
77          }
78          return match ? onMatch : onMismatch;
79      }
80  
81      private String getValue(final StructuredDataMessage data, final String key) {
82          if (key.equalsIgnoreCase("id")) {
83              return data.getId().toString();
84          } else if (key.equalsIgnoreCase("id.name")) {
85              return data.getId().getName();
86          } else if (key.equalsIgnoreCase("type")) {
87              return data.getType();
88          } else if (key.equalsIgnoreCase("message")) {
89              return data.getFormattedMessage();
90          } else {
91              return data.getData().get(key);
92          }
93      }
94  
95      /**
96       * Create the StructuredDataFilter.
97       * @param pairs Key and value pairs.
98       * @param oper The operator to perform. If not "or" the operation will be an "and".
99       * @param match The action to perform on a match.
100      * @param mismatch The action to perform on a mismatch.
101      * @return The StructuredDataFilter.
102      */
103     @PluginFactory
104     public static StructuredDataFilter createFilter(
105             @PluginElement("Pairs") final KeyValuePair[] pairs,
106             @PluginAttribute("operator") final String oper,
107             @PluginAttribute("onMatch") final String match,
108             @PluginAttribute("onMismatch") final String mismatch) {
109         if (pairs == null || pairs.length == 0) {
110             LOGGER.error("keys and values must be specified for the StructuredDataFilter");
111             return null;
112         }
113         final Map<String, List<String>> map = new HashMap<String, List<String>>();
114         for (final KeyValuePair pair : pairs) {
115             final String key = pair.getKey();
116             if (key == null) {
117                 LOGGER.error("A null key is not valid in MapFilter");
118                 continue;
119             }
120             final String value = pair.getValue();
121             if (value == null) {
122                 LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
123                 continue;
124             }
125             List<String> list = map.get(pair.getKey());
126             if (list != null) {
127                 list.add(value);
128             } else {
129                 list = new ArrayList<String>();
130                 list.add(value);
131                 map.put(pair.getKey(), list);
132             }
133         }
134         if (map.size() == 0) {
135             LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
136             return null;
137         }
138         final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
139         final Result onMatch = Result.toResult(match);
140         final Result onMismatch = Result.toResult(mismatch);
141         return new StructuredDataFilter(map, isAnd, onMatch, onMismatch);
142     }
143 }