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