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 long serialVersionUID = 1L;
48  
49      private static final int DEFAULT_PATTERN_FLAGS = 0;
50      private final Pattern pattern;
51      private final boolean useRawMessage;
52  
53      private RegexFilter(final boolean raw, final Pattern pattern, final Result onMatch, final Result onMismatch) {
54          super(onMatch, onMismatch);
55          this.pattern = pattern;
56          this.useRawMessage = raw;
57      }
58  
59      @Override
60      public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
61              final Object... params) {
62          return filter(msg);
63      }
64  
65      @Override
66      public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
67              final Throwable t) {
68          if (msg == null) {
69              return onMismatch;
70          }
71          return filter(msg.toString());
72      }
73  
74      @Override
75      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
76              final Throwable t) {
77          if (msg == null) {
78              return onMismatch;
79          }
80          final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
81          return filter(text);
82      }
83  
84      @Override
85      public Result filter(final LogEvent event) {
86          final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
87          return filter(text);
88      }
89  
90      private Result filter(final String msg) {
91          if (msg == null) {
92              return onMismatch;
93          }
94          final Matcher m = pattern.matcher(msg);
95          return m.matches() ? onMatch : onMismatch;
96      }
97  
98      @Override
99      public String toString() {
100         final StringBuilder sb = new StringBuilder();
101         sb.append("useRaw=").append(useRawMessage);
102         sb.append(", pattern=").append(pattern.toString());
103         return sb.toString();
104     }
105 
106     /**
107      * Create a Filter that matches a regular expression.
108      *
109      * @param regex
110      *        The regular expression to match.
111      * @param patternFlags
112      *        An array of Stirngs where each String is a {@link Pattern#compile(String, int)} compilation flag.
113      * @param useRawMsg
114      *        If true, the raw message will be used, otherwise the formatted message will be used.
115      * @param match
116      *        The action to perform when a match occurs.
117      * @param mismatch
118      *        The action to perform when a mismatch occurs.
119      * @return The RegexFilter.
120      * @throws IllegalAccessException
121      * @throws IllegalArgumentException
122      */
123     @PluginFactory
124     public static RegexFilter createFilter(
125             //@formatter:off
126             @PluginAttribute("regex") final String regex,
127             @PluginElement("PatternFlags") final String[] patternFlags,
128             @PluginAttribute("useRawMsg") final Boolean useRawMsg,
129             @PluginAttribute("onMatch") final Result match,
130             @PluginAttribute("onMismatch") final Result mismatch)
131             //@formatter:on
132             throws IllegalArgumentException, IllegalAccessException {
133         if (regex == null) {
134             LOGGER.error("A regular expression must be provided for RegexFilter");
135             return null;
136         }
137         return new RegexFilter(useRawMsg, Pattern.compile(regex, toPatternFlags(patternFlags)), match, mismatch);
138     }
139 
140     private static int toPatternFlags(final String[] patternFlags) throws IllegalArgumentException,
141             IllegalAccessException {
142         if (patternFlags == null || patternFlags.length == 0) {
143             return DEFAULT_PATTERN_FLAGS;
144         }
145         final Field[] fields = Pattern.class.getDeclaredFields();
146         final Comparator<Field> comparator = new Comparator<Field>() {
147 
148             @Override
149             public int compare(final Field f1, final Field f2) {
150                 return f1.getName().compareTo(f2.getName());
151             }
152         };
153         Arrays.sort(fields, comparator);
154         final String[] fieldNames = new String[fields.length];
155         for (int i = 0; i < fields.length; i++) {
156             fieldNames[i] = fields[i].getName();
157         }
158         int flags = DEFAULT_PATTERN_FLAGS;
159         for (final String test : patternFlags) {
160             final int index = Arrays.binarySearch(fieldNames, test);
161             if (index >= 0) {
162                 final Field field = fields[index];
163                 flags |= field.getInt(Pattern.class);
164             }
165         }
166         return flags;
167     }
168 }