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