1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j;
19
20 import org.apache.log4j.helpers.OptionConverter;
21 import org.apache.log4j.helpers.PatternConverter;
22 import org.apache.log4j.pattern.BridgePatternConverter;
23 import org.apache.log4j.spi.LoggingEvent;
24
25
26
27
28
29 /***
30 * This class is an enhanced version of org.apache.log4j.PatternLayout
31 * which was originally developed as part of the abandoned log4j 1.3
32 * effort and has been available in the extras companion.
33 * This pattern layout should be used in preference to
34 * org.apache.log4j.PatternLayout except when compatibility
35 * where PatternLayout has been extended either through subclassing
36 * or alternative pattern parsers.
37 *
38 *
39 * <p>A flexible layout configurable with pattern string. The goal of this class
40 * is to {@link #format format} a {@link LoggingEvent} and return the results
41 * in a {@link StringBuffer}. The format of the result depends on the
42 * <em>conversion pattern</em>.
43 * <p>
44 *
45 * <p>The conversion pattern is closely related to the conversion
46 * pattern of the printf function in C. A conversion pattern is
47 * composed of literal text and format control expressions called
48 * <em>conversion specifiers</em>.
49 *
50 * <p><i>Note that you are free to insert any literal text within the
51 * conversion pattern.</i>
52 * </p>
53
54 <p>Each conversion specifier starts with a percent sign (%) and is
55 followed by optional <em>format modifiers</em> and a <em>conversion
56 character</em>. The conversion character specifies the type of
57 data, e.g. category, priority, date, thread name. The format
58 modifiers control such things as field width, padding, left and
59 right justification. The following is a simple example.
60
61 <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume
62 that the log4j environment was set to use a EnhancedPatternLayout. Then the
63 statements
64 <pre>
65 Category root = Category.getRoot();
66 root.debug("Message 1");
67 root.warn("Message 2");
68 </pre>
69 would yield the output
70 <pre>
71 DEBUG [main]: Message 1
72 WARN [main]: Message 2
73 </pre>
74
75 <p>Note that there is no explicit separator between text and
76 conversion specifiers. The pattern parser knows when it has reached
77 the end of a conversion specifier when it reads a conversion
78 character. In the example above the conversion specifier
79 <b>%-5p</b> means the priority of the logging event should be left
80 justified to a width of five characters.
81
82 The recognized conversion characters are
83
84 <p>
85 <table border="1" CELLPADDING="8">
86 <th>Conversion Character</th>
87 <th>Effect</th>
88
89 <tr>
90 <td align=center><b>c</b></td>
91
92 <td>Used to output the category of the logging event. The
93 category conversion specifier can be optionally followed by
94 NameAbbreviator pattern.
95
96 <p>For example, for the category name "alpha.beta.gamma" the pattern
97 <b>%c{2}</b> will output the last two elements ("beta.gamma"),
98 <b>%c{-2}</b> will remove two elements leaving "gamma",
99 <b>%c{1.}</b> will output "a.b.gamma".
100
101 </td>
102 </tr>
103
104 <tr>
105 <td align=center><b>C</b></td>
106
107 <td>Used to output the fully qualified class name of the caller
108 issuing the logging request. This conversion specifier
109 can be optionally followed by <em>precision specifier</em>, that
110 is a decimal constant in brackets.
111
112 <td>Used to output the category of the logging event. The
113 category conversion specifier can be optionally followed by
114 NameAbbreviator pattern.
115
116 <p>For example, for the category name "alpha.beta.gamma" the pattern
117 <b>%c{2}</b> will output the last two elements ("beta.gamma"),
118 <b>%c{-2}</b> will remove two elements leaving "gamma",
119 <b>%c{1.}</b> will output "a.b.gamma".
120
121 <p><b>WARNING</b> Generating the caller class information is
122 slow. Thus, its use should be avoided unless execution speed is
123 not an issue.
124
125 </td>
126 </tr>
127
128 <tr> <td align=center><b>d</b></td> <td>Used to output the date of
129 the logging event. The date conversion specifier may be
130 followed by a set of braces containing a
131 date and time pattern strings {@link java.text.SimpleDateFormat},
132 <em>ABSOLUTE</em>, <em>DATE</em> or <em>ISO8601</em>
133 and a set of braces containing a time zone id per
134 {@link java.util.TimeZone#getTimeZone(String)}.
135 For example, <b>%d{HH:mm:ss,SSS}</b>,
136 <b>%d{dd MMM yyyy HH:mm:ss,SSS}</b>,
137 <b>%d{DATE}</b> or <b>%d{HH:mm:ss}{GMT+0}</b>. If no date format specifier is given then
138 ISO8601 format is assumed.
139 </td>
140 </tr>
141
142 <tr>
143 <td align=center><b>F</b></td>
144
145 <td>Used to output the file name where the logging request was
146 issued.
147
148 <p><b>WARNING</b> Generating caller location information is
149 extremely slow and should be avoided unless execution speed
150 is not an issue.
151
152 </tr>
153
154 <tr>
155 <td align=center><b>l</b></td>
156
157 <td>Used to output location information of the caller which generated
158 the logging event.
159
160 <p>The location information depends on the JVM implementation but
161 usually consists of the fully qualified name of the calling
162 method followed by the callers source the file name and line
163 number between parentheses.
164
165 <p>The location information can be very useful. However, its
166 generation is <em>extremely</em> slow and should be avoided
167 unless execution speed is not an issue.
168
169 </td>
170 </tr>
171
172 <tr>
173 <td align=center><b>L</b></td>
174
175 <td>Used to output the line number from where the logging request
176 was issued.
177
178 <p><b>WARNING</b> Generating caller location information is
179 extremely slow and should be avoided unless execution speed
180 is not an issue.
181
182 </tr>
183
184
185 <tr>
186 <td align=center><b>m</b></td>
187 <td>Used to output the application supplied message associated with
188 the logging event.</td>
189 </tr>
190
191 <tr>
192 <td align=center><b>M</b></td>
193
194 <td>Used to output the method name where the logging request was
195 issued.
196
197 <p><b>WARNING</b> Generating caller location information is
198 extremely slow and should be avoided unless execution speed
199 is not an issue.
200
201 </tr>
202
203 <tr>
204 <td align=center><b>n</b></td>
205
206 <td>Outputs the platform dependent line separator character or
207 characters.
208
209 <p>This conversion character offers practically the same
210 performance as using non-portable line separator strings such as
211 "\n", or "\r\n". Thus, it is the preferred way of specifying a
212 line separator.
213
214
215 </tr>
216
217 <tr>
218 <td align=center><b>p</b></td>
219 <td>Used to output the priority of the logging event.</td>
220 </tr>
221
222 <tr>
223
224 <td align=center><b>r</b></td>
225
226 <td>Used to output the number of milliseconds elapsed since the construction
227 of the layout until the creation of the logging event.</td>
228 </tr>
229
230
231 <tr>
232 <td align=center><b>t</b></td>
233
234 <td>Used to output the name of the thread that generated the
235 logging event.</td>
236
237 </tr>
238
239 <tr>
240
241 <td align=center><b>x</b></td>
242
243 <td>Used to output the NDC (nested diagnostic context) associated
244 with the thread that generated the logging event.
245 </td>
246 </tr>
247
248
249 <tr>
250 <td align=center><b>X</b></td>
251
252 <td>
253
254 <p>Used to output the MDC (mapped diagnostic context) associated
255 with the thread that generated the logging event. The <b>X</b>
256 conversion character can be followed by the key for the
257 map placed between braces, as in <b>%X{clientNumber}</b> where
258 <code>clientNumber</code> is the key. The value in the MDC
259 corresponding to the key will be output. If no additional sub-option
260 is specified, then the entire contents of the MDC key value pair set
261 is output using a format {{key1,val1},{key2,val2}}</p>
262
263 <p>See {@link MDC} class for more details.
264 </p>
265
266 </td>
267 </tr>
268
269 <tr>
270 <td align=center><b>properties</b></td>
271
272 <td>
273 <p>Used to output the Properties associated
274 with the logging event. The <b>properties</b>
275 conversion word can be followed by the key for the
276 map placed between braces, as in <b>%properties{application}</b> where
277 <code>application</code> is the key. The value in the Properties bundle
278 corresponding to the key will be output. If no additional sub-option
279 is specified, then the entire contents of the Properties key value pair set
280 is output using a format {{key1,val1},{key2,val2}}</p>
281 </td>
282 </tr>
283
284 <tr>
285 <td align=center><b>throwable</b></td>
286
287 <td>
288 <p>Used to output the Throwable trace that has been bound to the LoggingEvent, by
289 default this will output the full trace as one would normally
290 find by a call to Throwable.printStackTrace().
291 <b>%throwable{short}</b> or <b>%throwable{1}</b> will output the first line of
292 stack trace. <b>throwable{none}</b> or <b>throwable{0}</b> will suppress
293 the stack trace. <b>%throwable{n}</b> will output n lines of stack trace
294 if a positive integer or omit the last -n lines if a negative integer.
295 If no %throwable pattern is specified, the appender will take
296 responsibility to output the stack trace as it sees fit.</p>
297 </td>
298 </tr>
299
300 <tr>
301
302 <td align=center><b>%</b></td>
303
304 <td>The sequence %% outputs a single percent sign.
305 </td>
306 </tr>
307
308 </table>
309
310 <p>By default the relevant information is output as is. However,
311 with the aid of format modifiers it is possible to change the
312 minimum field width, the maximum field width, justification
313 and truncation.
314
315 <p>The optional format modifiers are placed between the percent sign
316 and the conversion character.
317
318 <p>The <em>left justification flag</em>, the minus sign (-),
319 the <em>right truncation flag</em>, the exclamation mark (!),
320 or any combination appear first. Followed by the
321 optional <em>minimum field width</em> modifier. This is a decimal
322 constant that represents the minimum number of characters to
323 output. If the data item requires fewer characters, it is padded on
324 either the left or the right until the minimum width is
325 reached. The default is to pad on the left (right justify) but you
326 can specify right padding with the left justification flag. The
327 padding character is space. If the data item is larger than the
328 minimum field width, the field is expanded to accommodate the
329 data. The value is never truncated.
330
331 <p>This behavior can be changed using the <em>maximum field
332 width</em> modifier which is designated by a period followed by a
333 decimal constant. If the data item is longer than the maximum
334 field, then the extra characters are removed from the
335 <em>beginning</em> of the data item and not from the end. For
336 example, it the maximum field width is eight and the data item is
337 ten characters long, then the first two characters of the data item
338 are dropped. This behavior deviates from the printf function in C
339 where truncation is done from the end. The <em>right truncation flag</em>,
340 described previously, will override this behavior.
341
342 <p>Below are various format modifier examples for the category
343 conversion specifier.
344
345 <p>
346 <TABLE BORDER=1 CELLPADDING=8>
347 <th>Format modifier
348 <th>left justify
349 <th>minimum width
350 <th>maximum width
351 <th>comment
352
353 <tr>
354 <td align=center>%20c</td>
355 <td align=center>false</td>
356 <td align=center>20</td>
357 <td align=center>none</td>
358
359 <td>Left pad with spaces if the category name is less than 20
360 characters long.
361
362 <tr> <td align=center>%-20c</td> <td align=center>true</td> <td
363 align=center>20</td> <td align=center>none</td> <td>Right pad with
364 spaces if the category name is less than 20 characters long.
365
366 <tr>
367 <td align=center>%.30c</td>
368 <td align=center>NA</td>
369 <td align=center>none</td>
370 <td align=center>30</td>
371
372 <td>Truncate from the beginning if the category name is longer than 30
373 characters.
374
375 <tr>
376 <td align=center>%!.30c</td>
377 <td align=center>NA</td>
378 <td align=center>none</td>
379 <td align=center>30</td>
380
381 <td>Truncate from the end if the category name is longer than 30
382 characters.
383
384 <tr>
385 <td align=center>%20.30c</td>
386 <td align=center>false</td>
387 <td align=center>20</td>
388 <td align=center>30</td>
389
390 <td>Left pad with spaces if the category name is shorter than 20
391 characters. However, if category name is longer than 30 characters,
392 then truncate from the beginning.
393
394 <tr>
395 <td align=center>%-20.30c</td>
396 <td align=center>true</td>
397 <td align=center>20</td>
398 <td align=center>30</td>
399
400 <td>Right pad with spaces if the category name is shorter than 20
401 characters. However, if category name is longer than 30 characters,
402 then truncate from the beginning.
403
404 </table>
405
406 <p>Below are some examples of conversion patterns.
407
408 <dl>
409
410 <p><dt><b>%r [%t] %-5p %c %x - %m%n</b>
411 <p><dd>This is essentially the TTCC layout.
412
413 <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m%n</b>
414
415 <p><dd>Similar to the TTCC layout except that the relative time is
416 right padded if less than 6 digits, thread name is right padded if
417 less than 15 characters and truncated if longer and the category
418 name is left padded if shorter than 30 characters and truncated if
419 longer.
420
421 </dl>
422
423 <p>The above text is largely inspired from Peter A. Darnell and
424 Philip E. Margolis' highly recommended book "C -- a Software
425 Engineering Approach", ISBN 0-387-97389-3.
426
427 @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a>
428 @author Ceki Gülcü
429
430
431 @since 1.2.16 */
432 public class EnhancedPatternLayout extends Layout {
433 /*** Default pattern string for log output. Currently set to the
434 string <b>"%m%n"</b> which just prints the application supplied
435 message. */
436 public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
437
438 /*** A conversion pattern equivalent to the TTCCCLayout.
439 Current value is <b>%r [%t] %p %c %x - %m%n</b>. */
440 public static final String TTCC_CONVERSION_PATTERN =
441 "%r [%t] %p %c %x - %m%n";
442
443 /***
444 * Initial size of internal buffer, no longer used.
445 * @deprecated since 1.3
446 */
447 protected final int BUF_SIZE = 256;
448
449 /***
450 * Maximum capacity of internal buffer, no longer used.
451 * @deprecated since 1.3
452 */
453 protected final int MAX_CAPACITY = 1024;
454
455 /***
456 * Customized pattern conversion rules are stored under this key in the
457 * {@link org.apache.log4j.spi.LoggerRepository LoggerRepository} object store.
458 */
459 public static final String PATTERN_RULE_REGISTRY = "PATTERN_RULE_REGISTRY";
460
461
462 /***
463 * Initial converter for pattern.
464 */
465 private PatternConverter head;
466
467 /***
468 * Conversion pattern.
469 */
470 private String conversionPattern;
471
472 /***
473 * True if any element in pattern formats information from exceptions.
474 */
475 private boolean handlesExceptions;
476
477 /***
478 Constructs a EnhancedPatternLayout using the DEFAULT_LAYOUT_PATTERN.
479
480 The default pattern just produces the application supplied message.
481 */
482 public EnhancedPatternLayout() {
483 this(DEFAULT_CONVERSION_PATTERN);
484 }
485
486 /***
487 * Constructs a EnhancedPatternLayout using the supplied conversion pattern.
488 * @param pattern conversion pattern.
489 */
490 public EnhancedPatternLayout(final String pattern) {
491 this.conversionPattern = pattern;
492 head = createPatternParser(
493 (pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse();
494 if (head instanceof BridgePatternConverter) {
495 handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable();
496 } else {
497 handlesExceptions = false;
498 }
499 }
500
501 /***
502 * Set the <b>ConversionPattern</b> option. This is the string which
503 * controls formatting and consists of a mix of literal content and
504 * conversion specifiers.
505 *
506 * @param conversionPattern conversion pattern.
507 */
508 public void setConversionPattern(final String conversionPattern) {
509 this.conversionPattern =
510 OptionConverter.convertSpecialChars(conversionPattern);
511 head = createPatternParser(this.conversionPattern).parse();
512 if (head instanceof BridgePatternConverter) {
513 handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable();
514 } else {
515 handlesExceptions = false;
516 }
517 }
518
519 /***
520 * Returns the value of the <b>ConversionPattern</b> option.
521 * @return conversion pattern.
522 */
523 public String getConversionPattern() {
524 return conversionPattern;
525 }
526
527
528 /***
529 Returns PatternParser used to parse the conversion string. Subclasses
530 may override this to return a subclass of PatternParser which recognize
531 custom conversion characters.
532
533 @since 0.9.0
534 */
535 protected org.apache.log4j.helpers.PatternParser createPatternParser(String pattern) {
536 return new org.apache.log4j.pattern.BridgePatternParser(pattern);
537 }
538
539
540 /***
541 Activates the conversion pattern. Do not forget to call this method after
542 you change the parameters of the EnhancedPatternLayout instance.
543 */
544 public void activateOptions() {
545
546 }
547
548
549 /***
550 * Formats a logging event to a writer.
551 * @param event logging event to be formatted.
552 */
553 public String format(final LoggingEvent event) {
554 StringBuffer buf = new StringBuffer();
555 for(PatternConverter c = head;
556 c != null;
557 c = c.next) {
558 c.format(buf, event);
559 }
560 return buf.toString();
561 }
562
563 /***
564 * Will return false if any of the conversion specifiers in the pattern
565 * handles {@link Exception Exceptions}.
566 * @return true if the pattern formats any information from exceptions.
567 */
568 public boolean ignoresThrowable() {
569 return !handlesExceptions;
570 }
571 }