1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j;
19
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 EnhancedPatternLayout 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.MyPatternLayout
38 @see org.apache.log4j.helpers.PatternParser
39 @see org.apache.log4j.EnhancedPatternLayout
40
41 @author Anders Kristensen
42 */
43 public class MyPatternParser extends PatternParser {
44
45 int counter = 0;
46
47 public
48 MyPatternParser(String 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 convert(LoggingEvent event) {
69 return String.valueOf(++counter);
70 }
71 }
72 }