KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log4j > PatternLayout


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.log4j;
18
19 import org.apache.log4j.Layout;
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    <p>The goal of this class is to {@link #format format} a {@link
33    LoggingEvent} and return the results as a String. The results
34    depend on the <em>conversion pattern</em>.
35
36    <p>The conversion pattern is closely related to the conversion
37    pattern of the printf function in C. A conversion pattern is
38    composed of literal text and format control expressions called
39    <em>conversion specifiers</em>.
40
41    <p><i>You are free to insert any literal text within the conversion
42    pattern.</i>
43
44    <p>Each conversion specifier starts with a percent sign (%) and is
45    followed by optional <em>format modifiers</em> and a <em>conversion
46    character</em>. The conversion character specifies the type of
47    data, e.g. category, priority, date, thread name. The format
48    modifiers control such things as field width, padding, left and
49    right justification. The following is a simple example.
50
51    <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume
52    that the log4j environment was set to use a PatternLayout. Then the
53    statements
54    <pre>
55    Category root = Category.getRoot();
56    root.debug("Message 1");
57    root.warn("Message 2");
58    </pre>
59    would yield the output
60    <pre>
61    DEBUG [main]: Message 1
62    WARN [main]: Message 2
63    </pre>
64
65    <p>Note that there is no explicit separator between text and
66    conversion specifiers. The pattern parser knows when it has reached
67    the end of a conversion specifier when it reads a conversion
68    character. In the example above the conversion specifier
69    <b>%-5p</b> means the priority of the logging event should be left
70    justified to a width of five characters.
71
72    The recognized conversion characters are
73
74    <p>
75    <table border="1" CELLPADDING="8">
76    <th>Conversion Character</th>
77    <th>Effect</th>
78
79    <tr>
80      <td align=center><b>c</b></td>
81
82      <td>Used to output the category of the logging event. The
83      category conversion specifier can be optionally followed by
84      <em>precision specifier</em>, that is a decimal constant in
85      brackets.
86
87      <p>If a precision specifier is given, then only the corresponding
88      number of right most components of the category name will be
89      printed. By default the category name is printed in full.
90
91      <p>For example, for the category name "a.b.c" the pattern
92      <b>%c{2}</b> will output "b.c".
93
94      </td>
95    </tr>
96
97    <tr>
98      <td align=center><b>C</b></td>
99
100      <td>Used to output the fully qualified class name of the caller
101      issuing the logging request. This conversion specifier
102      can be optionally followed by <em>precision specifier</em>, that
103      is a decimal constant in brackets.
104
105      <p>If a precision specifier is given, then only the corresponding
106      number of right most components of the class name will be
107      printed. By default the class name is output in fully qualified form.
108
109      <p>For example, for the class name "org.apache.xyz.SomeClass", the
110      pattern <b>%C{1}</b> will output "SomeClass".
111
112      <p><b>WARNING</b> Generating the caller class information is
113      slow. Thus, it's use should be avoided unless execution speed is
114      not an issue.
115
116      </td>
117      </tr>
118
119    <tr> <td align=center><b>d</b></td> <td>Used to output the date of
120      the logging event. The date conversion specifier may be
121      followed by a <em>date format specifier</em> enclosed between
122      braces. For example, <b>%d{HH:mm:ss,SSS}</b> or
123      <b>%d{dd&nbsp;MMM&nbsp;yyyy&nbsp;HH:mm:ss,SSS}</b>. If no
124      date format specifier is given then ISO8601 format is
125      assumed.
126
127      <p>The date format specifier admits the same syntax as the
128      time pattern string of the {@link
129      java.text.SimpleDateFormat}. Although part of the standard
130      JDK, the performance of <code>SimpleDateFormat</code> is
131      quite poor.
132
133      <p>For better results it is recommended to use the log4j date
134      formatters. These can be specified using one of the strings
135      "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link
136      org.apache.log4j.helpers.AbsoluteTimeDateFormat
137      AbsoluteTimeDateFormat}, {@link
138      org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat}
139      and respectively {@link
140      org.apache.log4j.helpers.ISO8601DateFormat
141      ISO8601DateFormat}. For example, <b>%d{ISO8601}</b> or
142      <b>%d{ABSOLUTE}</b>.
143
144      <p>These dedicated date formatters perform significantly
145      better than {@link java.text.SimpleDateFormat}.
146      </td>
147    </tr>
148
149    <tr>
150    <td align=center><b>F</b></td>
151
152    <td>Used to output the file name where the logging request was
153    issued.
154
155    <p><b>WARNING</b> Generating caller location information is
156    extremely slow. It's use should be avoided unless execution speed
157    is not an issue.
158
159    </tr>
160
161    <tr>
162    <td align=center><b>l</b></td>
163
164      <td>Used to output location information of the caller which generated
165      the logging event.
166
167      <p>The location information depends on the JVM implementation but
168      usually consists of the fully qualified name of the calling
169      method followed by the callers source the file name and line
170      number between parentheses.
171
172      <p>The location information can be very useful. However, it's
173      generation is <em>extremely</em> slow. It's use should be avoided
174      unless execution speed is not an issue.
175
176      </td>
177    </tr>
178
179    <tr>
180    <td align=center><b>L</b></td>
181
182    <td>Used to output the line number from where the logging request
183    was issued.
184
185    <p><b>WARNING</b> Generating caller location information is
186    extremely slow. It's use should be avoided unless execution speed
187    is not an issue.
188
189    </tr>
190
191
192    <tr>
193      <td align=center><b>m</b></td>
194      <td>Used to output the application supplied message associated with
195      the logging event.</td>
196    </tr>
197
198    <tr>
199    <td align=center><b>M</b></td>
200
201    <td>Used to output the method name where the logging request was
202    issued.
203
204    <p><b>WARNING</b> Generating caller location information is
205    extremely slow. It's use should be avoided unless execution speed
206    is not an issue.
207
208    </tr>
209
210    <tr>
211      <td align=center><b>n</b></td>
212
213      <td>Outputs the platform dependent line separator character or
214      characters.
215
216      <p>This conversion character offers practically the same
217      performance as using non-portable line separator strings such as
218      "\n", or "\r\n". Thus, it is the preferred way of specifying a
219      line separator.
220
221
222    </tr>
223
224    <tr>
225      <td align=center><b>p</b></td>
226      <td>Used to output the priority of the logging event.</td>
227    </tr>
228
229    <tr>
230
231      <td align=center><b>r</b></td>
232
233      <td>Used to output the number of milliseconds elapsed since the start
234      of the application until the creation of the logging event.</td>
235    </tr>
236
237
238    <tr>
239      <td align=center><b>t</b></td>
240
241      <td>Used to output the name of the thread that generated the
242      logging event.</td>
243
244    </tr>
245
246    <tr>
247
248      <td align=center><b>x</b></td>
249
250      <td>Used to output the NDC (nested diagnostic context) associated
251      with the thread that generated the logging event.
252      </td>
253    </tr>
254
255
256    <tr>
257      <td align=center><b>X</b></td>
258
259      <td>
260      
261      <p>Used to output the MDC (mapped diagnostic context) associated
262      with the thread that generated the logging event. The <b>X</b>
263      conversion character <em>must</em> be followed by the key for the
264      map placed between braces, as in <b>%X{clientNumber}</b> where
265      <code>clientNumber</code> is the key. The value in the MDC
266      corresponding to the key will be output.</p>
267      
268      <p>See {@link MDC} class for more details.
269      </p>
270      
271      </td>
272    </tr>
273
274    <tr>
275
276      <td align=center><b>%</b></td>
277
278      <td>The sequence %% outputs a single percent sign.
279      </td>
280    </tr>
281
282    </table>
283
284    <p>By default the relevant information is output as is. However,
285    with the aid of format modifiers it is possible to change the
286    minimum field width, the maximum field width and justification.
287
288    <p>The optional format modifier is placed between the percent sign
289    and the conversion character.
290
291    <p>The first optional format modifier is the <em>left justification
292    flag</em> which is just the minus (-) character. Then comes the
293    optional <em>minimum field width</em> modifier. This is a decimal
294    constant that represents the minimum number of characters to
295    output. If the data item requires fewer characters, it is padded on
296    either the left or the right until the minimum width is
297    reached. The default is to pad on the left (right justify) but you
298    can specify right padding with the left justification flag. The
299    padding character is space. If the data item is larger than the
300    minimum field width, the field is expanded to accommodate the
301    data. The value is never truncated.
302
303    <p>This behavior can be changed using the <em>maximum field
304    width</em> modifier which is designated by a period followed by a
305    decimal constant. If the data item is longer than the maximum
306    field, then the extra characters are removed from the
307    <em>beginning</em> of the data item and not from the end. For
308    example, it the maximum field width is eight and the data item is
309    ten characters long, then the first two characters of the data item
310    are dropped. This behavior deviates from the printf function in C
311    where truncation is done from the end.
312
313    <p>Below are various format modifier examples for the category
314    conversion specifier.
315
316    <p>
317    <TABLE BORDER=1 CELLPADDING=8>
318    <th>Format modifier
319    <th>left justify
320    <th>minimum width
321    <th>maximum width
322    <th>comment
323
324    <tr>
325    <td align=center>%20c</td>
326    <td align=center>false</td>
327    <td align=center>20</td>
328    <td align=center>none</td>
329
330    <td>Left pad with spaces if the category name is less than 20
331    characters long.
332
333    <tr> <td align=center>%-20c</td> <td align=center>true</td> <td
334    align=center>20</td> <td align=center>none</td> <td>Right pad with
335    spaces if the category name is less than 20 characters long.
336
337    <tr>
338    <td align=center>%.30c</td>
339    <td align=center>NA</td>
340    <td align=center>none</td>
341    <td align=center>30</td>
342
343    <td>Truncate from the beginning if the category name is longer than 30
344    characters.
345
346    <tr>
347    <td align=center>%20.30c</td>
348    <td align=center>false</td>
349    <td align=center>20</td>
350    <td align=center>30</td>
351
352    <td>Left pad with spaces if the category name is shorter than 20
353    characters. However, if category name is longer than 30 characters,
354    then truncate from the beginning.
355
356    <tr>
357    <td align=center>%-20.30c</td>
358    <td align=center>true</td>
359    <td align=center>20</td>
360    <td align=center>30</td>
361
362    <td>Right pad with spaces if the category name is shorter than 20
363    characters. However, if category name is longer than 30 characters,
364    then truncate from the beginning.
365
366    </table>
367
368    <p>Below are some examples of conversion patterns.
369
370    <dl>
371
372    <p><dt><b>%r [%t] %-5p %c %x - %m\n</b>
373    <p><dd>This is essentially the TTCC layout.
374
375    <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m\n</b>
376
377    <p><dd>Similar to the TTCC layout except that the relative time is
378    right padded if less than 6 digits, thread name is right padded if
379    less than 15 characters and truncated if longer and the category
380    name is left padded if shorter than 30 characters and truncated if
381    longer.
382
383   </dl>
384
385    <p>The above text is largely inspired from Peter A. Darnell and
386    Philip E. Margolis' highly recommended book "C -- a Software
387    Engineering Approach", ISBN 0-387-97389-3.
388
389    @author <a HREF="mailto:cakalijp@Maritz.com">James P. Cakalic</a>
390    @author Ceki G&uuml;lc&uuml;
391
392
393    @since 0.8.2 */

394 public class PatternLayout extends Layout {
395
396
397   /** Default pattern string for log output. Currently set to the
398       string <b>"%m%n"</b> which just prints the application supplied
399       message. */

400   public final static String JavaDoc DEFAULT_CONVERSION_PATTERN ="%m%n";
401
402   /** A conversion pattern equivalent to the TTCCCLayout.
403       Current value is <b>%r [%t] %p %c %x - %m%n</b>. */

404   public final static String JavaDoc TTCC_CONVERSION_PATTERN
405                                              = "%r [%t] %p %c %x - %m%n";
406
407
408   protected final int BUF_SIZE = 256;
409   protected final int MAX_CAPACITY = 1024;
410
411
412   // output buffer appended to when format() is invoked
413
private StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc(BUF_SIZE);
414
415   private String JavaDoc pattern;
416
417   private PatternConverter head;
418
419   private String JavaDoc timezone;
420
421   /**
422      Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.
423
424      The default pattern just produces the application supplied message.
425   */

426   public PatternLayout() {
427     this(DEFAULT_CONVERSION_PATTERN);
428   }
429
430   /**
431      Constructs a PatternLayout using the supplied conversion pattern.
432   */

433   public PatternLayout(String JavaDoc pattern) {
434     this.pattern = pattern;
435     head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN :
436                  pattern).parse();
437   }
438
439    /**
440      Set the <b>ConversionPattern</b> option. This is the string which
441      controls formatting and consists of a mix of literal content and
442      conversion specifiers.
443    */

444   public
445   void setConversionPattern(String JavaDoc conversionPattern) {
446     pattern = conversionPattern;
447     head = createPatternParser(conversionPattern).parse();
448   }
449
450   /**
451      Returns the value of the <b>ConversionPattern</b> option.
452    */

453   public
454   String JavaDoc getConversionPattern() {
455     return pattern;
456   }
457
458   /**
459      Does not do anything as options become effective
460   */

461   public
462   void activateOptions() {
463     // nothing to do.
464
}
465
466  /**
467      The PatternLayout does not handle the throwable contained within
468      {@link LoggingEvent LoggingEvents}. Thus, it returns
469      <code>true</code>.
470
471      @since 0.8.4 */

472   public
473   boolean ignoresThrowable() {
474     return true;
475   }
476
477   /**
478     Returns PatternParser used to parse the conversion string. Subclasses
479     may override this to return a subclass of PatternParser which recognize
480     custom conversion characters.
481
482     @since 0.9.0
483   */

484   protected PatternParser createPatternParser(String JavaDoc pattern) {
485     return new PatternParser(pattern);
486   }
487
488
489   /**
490      Produces a formatted string as specified by the conversion pattern.
491   */

492   public String JavaDoc format(LoggingEvent event) {
493     // Reset working stringbuffer
494
if(sbuf.capacity() > MAX_CAPACITY) {
495       sbuf = new StringBuffer JavaDoc(BUF_SIZE);
496     } else {
497       sbuf.setLength(0);
498     }
499
500     PatternConverter c = head;
501
502     while(c != null) {
503       c.format(sbuf, event);
504       c = c.next;
505     }
506     return sbuf.toString();
507   }
508 }
509
Popular Tags