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.util.regex.Matcher;
20  import java.util.regex.Pattern;
21  
22  import org.apache.logging.log4j.Level;
23  import org.apache.logging.log4j.Marker;
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.Logger;
26  import org.apache.logging.log4j.core.config.plugins.Plugin;
27  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
28  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
29  import org.apache.logging.log4j.message.Message;
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", category = "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          if (msg == null) {
61              return onMismatch;
62          }
63          return filter(msg.toString());
64      }
65  
66      @Override
67      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
68                           final Throwable t) {
69          if (msg == null) {
70              return onMismatch;
71          }
72          final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
73          return filter(text);
74      }
75  
76      @Override
77      public Result filter(final LogEvent event) {
78          final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
79          return filter(text);
80      }
81  
82      private Result filter(final String msg) {
83          if (msg == null) {
84              return onMismatch;
85          }
86          final Matcher m = pattern.matcher(msg);
87          return m.matches() ? onMatch : onMismatch;
88      }
89  
90      @Override
91      public String toString() {
92          final StringBuilder sb = new StringBuilder();
93          sb.append("useRaw=").append(useRawMessage);
94          sb.append(", pattern=").append(pattern.toString());
95          return sb.toString();
96      }
97  
98      /**
99       * Create a Filter that matches a regular expression.
100      * @param regex The regular expression to match.
101      * @param useRawMsg If true, the raw message will be used, otherwise the formatted message will be used.
102      * @param match The action to perform when a match occurs.
103      * @param mismatch The action to perform when a mismatch occurs.
104      * @return The RegexFilter.
105      */
106     @PluginFactory
107     public static RegexFilter createFilter(
108             @PluginAttribute("regex") final String regex,
109             @PluginAttribute("useRawMsg") final String useRawMsg,
110             @PluginAttribute("onMatch") final String match,
111             @PluginAttribute("onMismatch") final String mismatch) {
112 
113         if (regex == null) {
114             LOGGER.error("A regular expression must be provided for RegexFilter");
115             return null;
116         }
117         final boolean raw = Boolean.parseBoolean(useRawMsg);
118         Pattern pattern;
119         try {
120             pattern = Pattern.compile(regex);
121         } catch (final Exception ex) {
122             LOGGER.error("RegexFilter caught exception compiling pattern: " + regex + " cause: " + ex.getMessage());
123             return null;
124         }
125         final Result onMatch = Result.toResult(match);
126         final Result onMismatch = Result.toResult(mismatch);
127 
128         return new RegexFilter(raw, pattern, onMatch, onMismatch);
129     }
130 
131 }