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 org.apache.logging.log4j.Level;
20  import org.apache.logging.log4j.Marker;
21  import org.apache.logging.log4j.core.LogEvent;
22  import org.apache.logging.log4j.core.Logger;
23  import org.apache.logging.log4j.core.config.plugins.Plugin;
24  import org.apache.logging.log4j.core.config.plugins.PluginAttr;
25  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
26  import org.apache.logging.log4j.message.Message;
27  
28  import java.util.regex.Matcher;
29  import java.util.regex.Pattern;
30  
31  /**
32   * This filter returns the onMatch result if the message matches the regular expression.
33   *
34   * The "useRawMsg" attribute can be used to indicate whether the regular expression should be
35   * applied to the result of calling Message.getMessageFormat (true) or Message.getFormattedMessage()
36   * (false). The default is false.
37   *
38   */
39  @Plugin(name = "RegexFilter", type = "Core", elementType = "filter", printObject = true)
40  public final class RegexFilter extends AbstractFilter {
41  
42      private final Pattern pattern;
43      private final boolean useRawMessage;
44  
45      private RegexFilter(final boolean raw, final Pattern pattern, final Result onMatch, final Result onMismatch) {
46          super(onMatch, onMismatch);
47          this.pattern = pattern;
48          this.useRawMessage = raw;
49      }
50  
51      @Override
52      public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
53                           final Object... params) {
54          return filter(msg);
55      }
56  
57      @Override
58      public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
59                           final Throwable t) {
60          return filter(msg.toString());
61      }
62  
63      @Override
64      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
65                           final Throwable t) {
66          final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
67          return filter(text);
68      }
69  
70      @Override
71      public Result filter(final LogEvent event) {
72          final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
73          return filter(text);
74      }
75  
76      private Result filter(final String msg) {
77          if (msg == null) {
78              return onMismatch;
79          }
80          final Matcher m = pattern.matcher(msg);
81          return m.matches() ? onMatch : onMismatch;
82      }
83  
84      @Override
85      public String toString() {
86          final StringBuilder sb = new StringBuilder();
87          sb.append("useRaw=").append(useRawMessage);
88          sb.append(", pattern=").append(pattern.toString());
89          return sb.toString();
90      }
91  
92      /**
93       * Create a Filter that matches a regular expression.
94       * @param regex The regular expression to match.
95       * @param useRawMsg If true, the raw message will be used, otherwise the formatted message will be used.
96       * @param match The action to perform when a match occurs.
97       * @param mismatch The action to perform when a mismatch occurs.
98       * @return The RegexFilter.
99       */
100     @PluginFactory
101     public static RegexFilter createFilter(@PluginAttr("regex") final String regex,
102                                            @PluginAttr("useRawMsg") final String useRawMsg,
103                                             @PluginAttr("onMatch") final String match,
104                                             @PluginAttr("onMismatch") final String mismatch) {
105 
106         if (regex == null) {
107             LOGGER.error("A regular expression must be provided for RegexFilter");
108             return null;
109         }
110         final boolean raw = useRawMsg == null ? false : Boolean.parseBoolean(useRawMsg);
111         Pattern pattern;
112         try {
113             pattern = Pattern.compile(regex);
114         } catch (final Exception ex) {
115             LOGGER.error("RegexFilter caught exception compiling pattern: " + regex + " cause: " + ex.getMessage());
116             return null;
117         }
118         final Result onMatch = Result.toResult(match);
119         final Result onMismatch = Result.toResult(mismatch);
120 
121         return new RegexFilter(raw, pattern, onMatch, onMismatch);
122     }
123 
124 }