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