1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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ülcü
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 {
78 if(acceptOnMatch) {
79 return Filter.ACCEPT;
80 } else {
81 return Filter.DENY;
82 }
83 }
84 }
85 }