KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > examples > MyPatternParser


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package examples;
18
19 import org.apache.log4j.*;
20 import org.apache.log4j.helpers.FormattingInfo;
21 import org.apache.log4j.helpers.PatternConverter;
22 import org.apache.log4j.helpers.PatternParser;
23 import org.apache.log4j.spi.LoggingEvent;
24
25 /**
26   Example showing how to extend PatternParser to recognize additional
27   conversion characters. The examples shows that minimum and maximum
28   width and alignment settings apply for "extension" conversion
29   characters just as they do for PatternLayout recognized characters.
30   
31   <p>In this case MyPatternParser recognizes %# and outputs the value
32   of an internal counter which is also incremented at each call.
33
34   See <a HREF=doc-files/MyPatternParser.java><b>source</b></a> code
35    for more details.
36   
37   @see org.apache.log4j.examples.MyPatternLayout
38   @see org.apache.log4j.helpers.PatternParser
39   @see org.apache.log4j.PatternLayout
40
41   @author Anders Kristensen
42 */

43 public class MyPatternParser extends PatternParser {
44
45   int counter = 0;
46
47   public
48   MyPatternParser(String JavaDoc pattern) {
49     super(pattern);
50   }
51     
52   public
53   void finalizeConverter(char c) {
54     if (c == '#') {
55       addConverter(new UserDirPatternConverter(formattingInfo));
56       currentLiteral.setLength(0);
57     } else {
58       super.finalizeConverter(c);
59     }
60   }
61   
62   private class UserDirPatternConverter extends PatternConverter {
63     UserDirPatternConverter(FormattingInfo formattingInfo) {
64       super(formattingInfo);
65     }
66
67     public
68     String JavaDoc convert(LoggingEvent event) {
69       return String.valueOf(++counter);
70     }
71   }
72 }
73
Popular Tags