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  
18  package org.apache.log4j.filter;
19  
20  import org.apache.log4j.spi.Filter;
21  import org.apache.log4j.spi.LoggingEvent;
22  
23  /***
24     This is a very simple filter based on string matching.
25  
26     <p>The filter admits two options <b>StringToMatch</b> and
27     <b>AcceptOnMatch</b>. If there is a match between the value of the
28     StringToMatch option and the message of the {@link LoggingEvent},
29     then the {@link #decide(LoggingEvent)} method returns 
30     {@link org.apache.log4j.spi.Filter#ACCEPT} if
31     the <b>AcceptOnMatch</b> option value is true, if it is false then
32     {@link org.apache.log4j.spi.Filter#DENY} is returned. If there is no match, {@link
33     org.apache.log4j.spi.Filter#NEUTRAL} is returned.
34  
35     @author Ceki G&uuml;lc&uuml;
36  
37     @since 0.9.0 
38  */
39  public class StringMatchFilter extends Filter {
40    
41    boolean acceptOnMatch = true;
42    String stringToMatch;
43    
44    public
45    void setStringToMatch(String s) {
46      stringToMatch = s;
47    }
48    
49    public
50    String getStringToMatch() {
51      return stringToMatch;
52    }
53    
54    public
55    void setAcceptOnMatch(boolean acceptOnMatch) {
56      this.acceptOnMatch = acceptOnMatch;
57    }
58    
59    public
60    boolean getAcceptOnMatch() {
61      return acceptOnMatch;
62    }
63  
64    /***
65       Returns {@link Filter#NEUTRAL} is there is no string match.
66     */
67    public
68    int decide(LoggingEvent event) {
69      String msg = event.getRenderedMessage();
70  
71      if(msg == null ||  stringToMatch == null)
72        return Filter.NEUTRAL;
73      
74  
75      if( msg.indexOf(stringToMatch) == -1 ) {
76        return Filter.NEUTRAL;
77      } else { // we've got a match
78        if(acceptOnMatch) {
79  	return Filter.ACCEPT;
80        } else {
81  	return Filter.DENY;
82        }
83      }
84    }
85  }