1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.varia;
19
20 import org.apache.log4j.spi.Filter;
21 import org.apache.log4j.spi.LoggingEvent;
22 import org.apache.log4j.helpers.OptionConverter;
23
24 /***
25 * This is a very simple filter based on string matching.
26 *
27 * <p>The filter admits two options <b>StringToMatch</b> and
28 * <b>AcceptOnMatch</b>. If there is a match between the value of the
29 * StringToMatch option and the message of the {@link org.apache.log4j.spi.LoggingEvent},
30 * then the {@link #decide(LoggingEvent)} method returns {@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 * @since 0.9.0
37 */
38 public class StringMatchFilter extends Filter {
39
40 /***
41 @deprecated Options are now handled using the JavaBeans paradigm.
42 This constant is not longer needed and will be removed in the
43 <em>near</em> term.
44 */
45 public static final String STRING_TO_MATCH_OPTION = "StringToMatch";
46
47 /***
48 @deprecated Options are now handled using the JavaBeans paradigm.
49 This constant is not longer needed and will be removed in the
50 <em>near</em> term.
51 */
52 public static final String ACCEPT_ON_MATCH_OPTION = "AcceptOnMatch";
53
54 boolean acceptOnMatch = true;
55 String stringToMatch;
56
57 /***
58 @deprecated We now use JavaBeans introspection to configure
59 components. Options strings are no longer needed.
60 */
61 public
62 String[] getOptionStrings() {
63 return new String[] {STRING_TO_MATCH_OPTION, ACCEPT_ON_MATCH_OPTION};
64 }
65
66 /***
67 @deprecated Use the setter method for the option directly instead
68 of the generic <code>setOption</code> method.
69 */
70 public
71 void setOption(String key, String value) {
72
73 if(key.equalsIgnoreCase(STRING_TO_MATCH_OPTION)) {
74 stringToMatch = value;
75 } else if (key.equalsIgnoreCase(ACCEPT_ON_MATCH_OPTION)) {
76 acceptOnMatch = OptionConverter.toBoolean(value, acceptOnMatch);
77 }
78 }
79
80 public
81 void setStringToMatch(String s) {
82 stringToMatch = s;
83 }
84
85 public
86 String getStringToMatch() {
87 return stringToMatch;
88 }
89
90 public
91 void setAcceptOnMatch(boolean acceptOnMatch) {
92 this.acceptOnMatch = acceptOnMatch;
93 }
94
95 public
96 boolean getAcceptOnMatch() {
97 return acceptOnMatch;
98 }
99
100 /***
101 Returns {@link Filter#NEUTRAL} is there is no string match.
102 */
103 public
104 int decide(LoggingEvent event) {
105 String msg = event.getRenderedMessage();
106
107 if(msg == null || stringToMatch == null)
108 return Filter.NEUTRAL;
109
110
111 if( msg.indexOf(stringToMatch) == -1 ) {
112 return Filter.NEUTRAL;
113 } else {
114 if(acceptOnMatch) {
115 return Filter.ACCEPT;
116 } else {
117 return Filter.DENY;
118 }
119 }
120 }
121 }