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