1 17 package org.apache.log.format; 18 19 import org.apache.log.ContextMap; 20 import org.apache.log.LogEvent; 21 import org.apache.log.Logger; 22 import org.apache.log.util.StackIntrospector; 23 24 39 public class ExtendedPatternFormatter 40 extends PatternFormatter 41 { 42 private static final int TYPE_METHOD = MAX_TYPE + 1; 43 private static final int TYPE_THREAD = MAX_TYPE + 2; 44 45 private static final String TYPE_METHOD_STR = "method"; 46 private static final String TYPE_THREAD_STR = "thread"; 47 48 private int m_callStackOffset = 0; 49 50 54 public ExtendedPatternFormatter( final String format ) 55 { 56 this( format, 0 ); 57 } 58 59 65 public ExtendedPatternFormatter( final String format, final int callStackOffset ) 66 { 67 super( format ); 68 m_callStackOffset = callStackOffset; 69 } 70 71 77 protected int getTypeIdFor( final String type ) 78 { 79 if( type.equalsIgnoreCase( TYPE_METHOD_STR ) ) 80 { 81 return TYPE_METHOD; 82 } 83 else if( type.equalsIgnoreCase( TYPE_THREAD_STR ) ) 84 { 85 return TYPE_THREAD; 86 } 87 else 88 { 89 return super.getTypeIdFor( type ); 90 } 91 } 92 93 100 protected String formatPatternRun( final LogEvent event, final PatternRun run ) 101 { 102 switch( run.m_type ) 103 { 104 case TYPE_METHOD: 105 return getMethod( event ); 106 case TYPE_THREAD: 107 return getThread( event ); 108 default: 109 return super.formatPatternRun( event, run ); 110 } 111 } 112 113 119 private String getMethod( final LogEvent event ) 120 { 121 final ContextMap map = event.getContextMap(); 122 if( null != map ) 123 { 124 final Object object = map.get( "method" ); 125 if( null != object ) 126 { 127 return object.toString(); 128 } 129 } 130 131 final Class clazz = StackIntrospector.getCallerClass( Logger.class, m_callStackOffset - 1 ); 134 if( null == clazz ) 135 { 136 return "UnknownMethod"; 137 } 138 139 final String result = StackIntrospector.getCallerMethod( clazz ); 140 if( null == result ) 141 { 142 return "UnknownMethod"; 143 } 144 return result; 145 } 146 147 153 private String getThread( final LogEvent event ) 154 { 155 final ContextMap map = event.getContextMap(); 156 if( null != map ) 157 { 158 final Object object = map.get( "thread" ); 159 if( null != object ) 160 { 161 return object.toString(); 162 } 163 } 164 165 return Thread.currentThread().getName(); 166 } 167 } 168 | Popular Tags |