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.lang.reflect.Field;
20  import java.util.Arrays;
21  import java.util.Comparator;
22  import java.util.regex.Matcher;
23  import java.util.regex.Pattern;
24  
25  import org.apache.logging.log4j.Level;
26  import org.apache.logging.log4j.Marker;
27  import org.apache.logging.log4j.core.Filter;
28  import org.apache.logging.log4j.core.LogEvent;
29  import org.apache.logging.log4j.core.Logger;
30  import org.apache.logging.log4j.core.config.Node;
31  import org.apache.logging.log4j.core.config.plugins.Plugin;
32  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
33  import org.apache.logging.log4j.core.config.plugins.PluginElement;
34  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
35  import org.apache.logging.log4j.message.Message;
36  
37  /**
38   * This filter returns the onMatch result if the message matches the regular expression.
39   *
40   * The "useRawMsg" attribute can be used to indicate whether the regular expression should be applied to the result of
41   * calling Message.getMessageFormat (true) or Message.getFormattedMessage() (false). The default is false.
42   *
43   */
44  @Plugin(name = "RegexFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
45  public final class RegexFilter extends AbstractFilter {
46  
47      private static final int DEFAULT_PATTERN_FLAGS = 0;
48      private final Pattern pattern;
49      private final boolean useRawMessage;
50  
51      private RegexFilter(final boolean raw, final Pattern pattern, final Result onMatch, final Result onMismatch) {
52          super(onMatch, onMismatch);
53          this.pattern = pattern;
54          this.useRawMessage = raw;
55      }
56  
57      @Override
58      public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
59              final Object... params) {
60          return filter(msg);
61      }
62  
63      @Override
64      public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
65              final Throwable t) {
66          if (msg == null) {
67              return onMismatch;
68          }
69          return filter(msg.toString());
70      }
71  
72      @Override
73      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
74              final Throwable t) {
75          if (msg == null) {
76              return onMismatch;
77          }
78          final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
79          return filter(text);
80      }
81  
82      @Override
83      public Result filter(final LogEvent event) {
84          final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
85          return filter(text);
86      }
87  
88      private Result filter(final String msg) {
89          if (msg == null) {
90              return onMismatch;
91          }
92          final Matcher m = pattern.matcher(msg);
93          return m.matches() ? onMatch : onMismatch;
94      }
95  
96      @Override
97      public String toString() {
98          final StringBuilder sb = new StringBuilder();
99          sb.append("useRaw=").append(useRawMessage);
100         sb.append(", pattern=").append(pattern.toString());
101         return sb.toString();
102     }
103 
104     /**
105      * Creates a Filter that matches a regular expression.
106      *
107      * @param regex
108      *        The regular expression to match.
109      * @param patternFlags
110      *        An array of Stirngs where each String is a {@link Pattern#compile(String, int)} compilation flag.
111      * @param useRawMsg
112      *        If true, the raw message will be used, otherwise the formatted message will be used.
113      * @param match
114      *        The action to perform when a match occurs.
115      * @param mismatch
116      *        The action to perform when a mismatch occurs.
117      * @return The RegexFilter.
118      * @throws IllegalAccessException
119      * @throws IllegalArgumentException
120      */
121     // TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
122     @PluginFactory
123     public static RegexFilter createFilter(
124             //@formatter:off
125             @PluginAttribute("regex") final String regex,
126             @PluginElement("PatternFlags") final String[] patternFlags,
127             @PluginAttribute("useRawMsg") final Boolean useRawMsg,
128             @PluginAttribute("onMatch") final Result match,
129             @PluginAttribute("onMismatch") final Result mismatch)
130             //@formatter:on
131             throws IllegalArgumentException, IllegalAccessException {
132         if (regex == null) {
133             LOGGER.error("A regular expression must be provided for RegexFilter");
134             return null;
135         }
136         return new RegexFilter(useRawMsg, Pattern.compile(regex, toPatternFlags(patternFlags)), match, mismatch);
137     }
138 
139     private static int toPatternFlags(final String[] patternFlags) throws IllegalArgumentException,
140             IllegalAccessException {
141         if (patternFlags == null || patternFlags.length == 0) {
142             return DEFAULT_PATTERN_FLAGS;
143         }
144         final Field[] fields = Pattern.class.getDeclaredFields();
145         final Comparator<Field> comparator = new Comparator<Field>() {
146 
147             @Override
148             public int compare(final Field f1, final Field f2) {
149                 return f1.getName().compareTo(f2.getName());
150             }
151         };
152         Arrays.sort(fields, comparator);
153         final String[] fieldNames = new String[fields.length];
154         for (int i = 0; i < fields.length; i++) {
155             fieldNames[i] = fields[i].getName();
156         }
157         int flags = DEFAULT_PATTERN_FLAGS;
158         for (final String test : patternFlags) {
159             final int index = Arrays.binarySearch(fieldNames, test);
160             if (index >= 0) {
161                 final Field field = fields[index];
162                 flags |= field.getInt(Pattern.class);
163             }
164         }
165         return flags;
166     }
167 }