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; 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 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 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 }