View Javadoc

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.spi.LoggingEvent;
21  import org.apache.log4j.helpers.PatternParser;
22  import org.apache.log4j.helpers.PatternConverter;
23  
24  
25  // Contributors:   Nelson Minar <nelson@monkey.org>
26  //                 Anders Kristensen <akristensen@dynamicsoft.com>
27  
28  /**
29  
30     A flexible layout configurable with pattern string.
31     
32     This code is known to have synchronization and other issues
33     which are not present in org.apache.log4j.EnhancedPatternLayout.
34     EnhancedPatternLayout should be used in preference to PatternLayout.
35     EnhancedPatternLayout is distributed in the log4j extras companion.
36  
37     <p>The goal of this class is to {@link #format format} a {@link
38     LoggingEvent} and return the results as a String. The results
39     depend on the <em>conversion pattern</em>.
40  
41     <p>The conversion pattern is closely related to the conversion
42     pattern of the printf function in C. A conversion pattern is
43     composed of literal text and format control expressions called
44     <em>conversion specifiers</em>.
45  
46     <p><i>You are free to insert any literal text within the conversion
47     pattern.</i>
48  
49     <p>Each conversion specifier starts with a percent sign (%) and is
50     followed by optional <em>format modifiers</em> and a <em>conversion
51     character</em>. The conversion character specifies the type of
52     data, e.g. category, priority, date, thread name. The format
53     modifiers control such things as field width, padding, left and
54     right justification. The following is a simple example.
55  
56     <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume
57     that the log4j environment was set to use a PatternLayout. Then the
58     statements
59     <pre>
60     Category root = Category.getRoot();
61     root.debug("Message 1");
62     root.warn("Message 2");
63     </pre>
64     would yield the output
65     <pre>
66     DEBUG [main]: Message 1
67     WARN  [main]: Message 2
68     </pre>
69  
70     <p>Note that there is no explicit separator between text and
71     conversion specifiers. The pattern parser knows when it has reached
72     the end of a conversion specifier when it reads a conversion
73     character. In the example above the conversion specifier
74     <b>%-5p</b> means the priority of the logging event should be left
75     justified to a width of five characters.
76  
77     The recognized conversion characters are
78  
79     <p>
80     <table border="1" CELLPADDING="8">
81     <th>Conversion Character</th>
82     <th>Effect</th>
83  
84     <tr>
85       <td align=center><b>c</b></td>
86  
87       <td>Used to output the category of the logging event. The
88       category conversion specifier can be optionally followed by
89       <em>precision specifier</em>, that is a decimal constant in
90       brackets.
91  
92       <p>If a precision specifier is given, then only the corresponding
93       number of right most components of the category name will be
94       printed. By default the category name is printed in full.
95  
96       <p>For example, for the category name "a.b.c" the pattern
97       <b>%c{2}</b> will output "b.c".
98  
99       </td>
100    </tr>
101 
102    <tr>
103      <td align=center><b>C</b></td>
104 
105      <td>Used to output the fully qualified class name of the caller
106      issuing the logging request. This conversion specifier
107      can be optionally followed by <em>precision specifier</em>, that
108      is a decimal constant in brackets.
109 
110      <p>If a precision specifier is given, then only the corresponding
111      number of right most components of the class name will be
112      printed. By default the class name is output in fully qualified form.
113 
114      <p>For example, for the class name "org.apache.xyz.SomeClass", the
115      pattern <b>%C{1}</b> will output "SomeClass".
116 
117      <p><b>WARNING</b> Generating the caller class information is
118      slow. Thus, use should be avoided unless execution speed is
119      not an issue.
120 
121      </td>
122      </tr>
123 
124    <tr> <td align=center><b>d</b></td> <td>Used to output the date of
125 	 the logging event. The date conversion specifier may be
126 	 followed by a <em>date format specifier</em> enclosed between
127 	 braces. For example, <b>%d{HH:mm:ss,SSS}</b> or
128 	 <b>%d{dd&nbsp;MMM&nbsp;yyyy&nbsp;HH:mm:ss,SSS}</b>.  If no
129 	 date format specifier is given then ISO8601 format is
130 	 assumed.
131 
132 	 <p>The date format specifier admits the same syntax as the
133 	 time pattern string of the {@link
134 	 java.text.SimpleDateFormat}. Although part of the standard
135 	 JDK, the performance of <code>SimpleDateFormat</code> is
136 	 quite poor.
137 
138 	 <p>For better results it is recommended to use the log4j date
139 	 formatters. These can be specified using one of the strings
140 	 "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link
141 	 org.apache.log4j.helpers.AbsoluteTimeDateFormat
142 	 AbsoluteTimeDateFormat}, {@link
143 	 org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat}
144 	 and respectively {@link
145 	 org.apache.log4j.helpers.ISO8601DateFormat
146 	 ISO8601DateFormat}. For example, <b>%d{ISO8601}</b> or
147 	 <b>%d{ABSOLUTE}</b>.
148 
149 	 <p>These dedicated date formatters perform significantly
150 	 better than {@link java.text.SimpleDateFormat}.
151      </td>
152    </tr>
153 
154    <tr>
155    <td align=center><b>F</b></td>
156 
157    <td>Used to output the file name where the logging request was
158    issued.
159 
160    <p><b>WARNING</b> Generating caller location information is
161    extremely slow and should be avoided unless execution speed
162    is not an issue.
163 
164    </tr>
165 
166    <tr>
167    <td align=center><b>l</b></td>
168 
169      <td>Used to output location information of the caller which generated
170      the logging event.
171 
172      <p>The location information depends on the JVM implementation but
173      usually consists of the fully qualified name of the calling
174      method followed by the callers source the file name and line
175      number between parentheses.
176 
177      <p>The location information can be very useful. However, its
178      generation is <em>extremely</em> slow and should be avoided
179      unless execution speed is not an issue.
180 
181      </td>
182    </tr>
183 
184    <tr>
185    <td align=center><b>L</b></td>
186 
187    <td>Used to output the line number from where the logging request
188    was issued.
189 
190    <p><b>WARNING</b> Generating caller location information is
191    extremely slow and should be avoided unless execution speed
192    is not an issue.
193 
194    </tr>
195 
196 
197    <tr>
198      <td align=center><b>m</b></td>
199      <td>Used to output the application supplied message associated with
200      the logging event.</td>
201    </tr>
202 
203    <tr>
204    <td align=center><b>M</b></td>
205 
206    <td>Used to output the method name where the logging request was
207    issued.
208 
209    <p><b>WARNING</b> Generating caller location information is
210    extremely slow and should be avoided unless execution speed
211    is not an issue.
212 
213    </tr>
214 
215    <tr>
216      <td align=center><b>n</b></td>
217 
218      <td>Outputs the platform dependent line separator character or
219      characters.
220 
221      <p>This conversion character offers practically the same
222      performance as using non-portable line separator strings such as
223      "\n", or "\r\n". Thus, it is the preferred way of specifying a
224      line separator.
225 
226 
227    </tr>
228 
229    <tr>
230      <td align=center><b>p</b></td>
231      <td>Used to output the priority of the logging event.</td>
232    </tr>
233 
234    <tr>
235 
236      <td align=center><b>r</b></td>
237 
238      <td>Used to output the number of milliseconds elapsed from the construction 
239      of the layout until the creation of the logging event.</td>
240    </tr>
241 
242 
243    <tr>
244      <td align=center><b>t</b></td>
245 
246      <td>Used to output the name of the thread that generated the
247      logging event.</td>
248 
249    </tr>
250 
251    <tr>
252 
253      <td align=center><b>x</b></td>
254 
255      <td>Used to output the NDC (nested diagnostic context) associated
256      with the thread that generated the logging event.
257      </td>
258    </tr>
259 
260 
261    <tr>
262      <td align=center><b>X</b></td>
263 
264      <td> 
265      
266      <p>Used to output the MDC (mapped diagnostic context) associated
267      with the thread that generated the logging event. The <b>X</b>
268      conversion character <em>must</em> be followed by the key for the
269      map placed between braces, as in <b>%X{clientNumber}</b> where
270      <code>clientNumber</code> is the key. The value in the MDC
271      corresponding to the key will be output.</p>
272      
273      <p>See {@link MDC} class for more details.
274      </p>
275      
276      </td>
277    </tr>
278 
279    <tr>
280 
281      <td align=center><b>%</b></td>
282 
283      <td>The sequence %% outputs a single percent sign.
284      </td>
285    </tr>
286 
287    </table>
288 
289    <p>By default the relevant information is output as is. However,
290    with the aid of format modifiers it is possible to change the
291    minimum field width, the maximum field width and justification.
292 
293    <p>The optional format modifier is placed between the percent sign
294    and the conversion character.
295 
296    <p>The first optional format modifier is the <em>left justification
297    flag</em> which is just the minus (-) character. Then comes the
298    optional <em>minimum field width</em> modifier. This is a decimal
299    constant that represents the minimum number of characters to
300    output. If the data item requires fewer characters, it is padded on
301    either the left or the right until the minimum width is
302    reached. The default is to pad on the left (right justify) but you
303    can specify right padding with the left justification flag. The
304    padding character is space. If the data item is larger than the
305    minimum field width, the field is expanded to accommodate the
306    data. The value is never truncated.
307 
308    <p>This behavior can be changed using the <em>maximum field
309    width</em> modifier which is designated by a period followed by a
310    decimal constant. If the data item is longer than the maximum
311    field, then the extra characters are removed from the
312    <em>beginning</em> of the data item and not from the end. For
313    example, it the maximum field width is eight and the data item is
314    ten characters long, then the first two characters of the data item
315    are dropped. This behavior deviates from the printf function in C
316    where truncation is done from the end.
317 
318    <p>Below are various format modifier examples for the category
319    conversion specifier.
320 
321    <p>
322    <TABLE BORDER=1 CELLPADDING=8>
323    <th>Format modifier
324    <th>left justify
325    <th>minimum width
326    <th>maximum width
327    <th>comment
328 
329    <tr>
330    <td align=center>%20c</td>
331    <td align=center>false</td>
332    <td align=center>20</td>
333    <td align=center>none</td>
334 
335    <td>Left pad with spaces if the category name is less than 20
336    characters long.
337 
338    <tr> <td align=center>%-20c</td> <td align=center>true</td> <td
339    align=center>20</td> <td align=center>none</td> <td>Right pad with
340    spaces if the category name is less than 20 characters long.
341 
342    <tr>
343    <td align=center>%.30c</td>
344    <td align=center>NA</td>
345    <td align=center>none</td>
346    <td align=center>30</td>
347 
348    <td>Truncate from the beginning if the category name is longer than 30
349    characters.
350 
351    <tr>
352    <td align=center>%20.30c</td>
353    <td align=center>false</td>
354    <td align=center>20</td>
355    <td align=center>30</td>
356 
357    <td>Left pad with spaces if the category name is shorter than 20
358    characters. However, if category name is longer than 30 characters,
359    then truncate from the beginning.
360 
361    <tr>
362    <td align=center>%-20.30c</td>
363    <td align=center>true</td>
364    <td align=center>20</td>
365    <td align=center>30</td>
366 
367    <td>Right pad with spaces if the category name is shorter than 20
368    characters. However, if category name is longer than 30 characters,
369    then truncate from the beginning.
370 
371    </table>
372 
373    <p>Below are some examples of conversion patterns.
374 
375    <dl>
376 
377    <p><dt><b>%r [%t] %-5p %c %x - %m%n</b>
378    <p><dd>This is essentially the TTCC layout.
379 
380    <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m%n</b>
381 
382    <p><dd>Similar to the TTCC layout except that the relative time is
383    right padded if less than 6 digits, thread name is right padded if
384    less than 15 characters and truncated if longer and the category
385    name is left padded if shorter than 30 characters and truncated if
386    longer.
387 
388   </dl>
389 
390    <p>The above text is largely inspired from Peter A. Darnell and
391    Philip E. Margolis' highly recommended book "C -- a Software
392    Engineering Approach", ISBN 0-387-97389-3.
393 
394    @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a>
395    @author Ceki G&uuml;lc&uuml;
396 
397 
398    @since 0.8.2 */
399 public class PatternLayout extends Layout {
400 
401 
402   /** Default pattern string for log output. Currently set to the
403       string <b>"%m%n"</b> which just prints the application supplied
404       message. */
405   public final static String DEFAULT_CONVERSION_PATTERN ="%m%n";
406 
407   /** A conversion pattern equivalent to the TTCCCLayout.
408       Current value is <b>%r [%t] %p %c %x - %m%n</b>. */
409   public final static String TTCC_CONVERSION_PATTERN
410                                              = "%r [%t] %p %c %x - %m%n";
411 
412 
413   protected final int BUF_SIZE = 256;
414   protected final int MAX_CAPACITY = 1024;
415 
416 
417   // output buffer appended to when format() is invoked
418   private StringBuffer sbuf = new StringBuffer(BUF_SIZE);
419 
420   private String pattern;
421 
422   private PatternConverter head;
423 
424   /**
425      Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.
426 
427      The default pattern just produces the application supplied message.
428   */
429   public PatternLayout() {
430     this(DEFAULT_CONVERSION_PATTERN);
431   }
432 
433   /**
434      Constructs a PatternLayout using the supplied conversion pattern.
435   */
436   public PatternLayout(String pattern) {
437     this.pattern = pattern;
438     head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN :
439 			     pattern).parse();
440   }
441 
442    /**
443      Set the <b>ConversionPattern</b> option. This is the string which
444      controls formatting and consists of a mix of literal content and
445      conversion specifiers.
446    */
447   public
448   void setConversionPattern(String conversionPattern) {
449     pattern = conversionPattern;
450     head = createPatternParser(conversionPattern).parse();
451   }
452 
453   /**
454      Returns the value of the <b>ConversionPattern</b> option.
455    */
456   public
457   String getConversionPattern() {
458     return pattern;
459   }
460 
461   /**
462      Does not do anything as options become effective
463   */
464   public
465   void activateOptions() {
466     // nothing to do.
467   }
468 
469  /**
470      The PatternLayout does not handle the throwable contained within
471      {@link LoggingEvent LoggingEvents}. Thus, it returns
472      <code>true</code>.
473 
474      @since 0.8.4 */
475   public
476   boolean ignoresThrowable() {
477     return true;
478   }
479 
480   /**
481     Returns PatternParser used to parse the conversion string. Subclasses
482     may override this to return a subclass of PatternParser which recognize
483     custom conversion characters.
484 
485     @since 0.9.0
486   */
487   protected PatternParser createPatternParser(String pattern) {
488     return new PatternParser(pattern);
489   }
490 
491 
492   /**
493      Produces a formatted string as specified by the conversion pattern.
494   */
495   public String format(LoggingEvent event) {
496     // Reset working stringbuffer
497     if(sbuf.capacity() > MAX_CAPACITY) {
498       sbuf = new StringBuffer(BUF_SIZE);
499     } else {
500       sbuf.setLength(0);
501     }
502 
503     PatternConverter c = head;
504 
505     while(c != null) {
506       c.format(sbuf, event);
507       c = c.next;
508     }
509     return sbuf.toString();
510   }
511 }