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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.apache.log4j;
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;
26 // Contributors: Nelson Minar <nelson@monkey.org>
27 // Anders Kristensen <akristensen@dynamicsoft.com>
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.
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>.
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>.
50 * <p><i>Note that you are free to insert any literal text within the
51 * conversion pattern.</i>
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.
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
65 Category root = Category.getRoot();
66 root.debug("Message 1");
67 root.warn("Message 2");
69 would yield the output
71 DEBUG [main]: Message 1
72 WARN [main]: Message 2
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.
82 The recognized conversion characters are
85 <table border="1" CELLPADDING="8">
86 <th>Conversion Character</th>
90 <td align=center><b>c</b></td>
92 <td>Used to output the category of the logging event. The
93 category conversion specifier can be optionally followed by
94 NameAbbreviator pattern.
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".
105 <td align=center><b>C</b></td>
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.
112 <td>Used to output the category of the logging event. The
113 category conversion specifier can be optionally followed by
114 NameAbbreviator pattern.
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".
121 <p><b>WARNING</b> Generating the caller class information is
122 slow. Thus, its use should be avoided unless execution speed is
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.
143 <td align=center><b>F</b></td>
145 <td>Used to output the file name where the logging request was
148 <p><b>WARNING</b> Generating caller location information is
149 extremely slow and should be avoided unless execution speed
155 <td align=center><b>l</b></td>
157 <td>Used to output location information of the caller which generated
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.
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.
173 <td align=center><b>L</b></td>
175 <td>Used to output the line number from where the logging request
178 <p><b>WARNING</b> Generating caller location information is
179 extremely slow and should be avoided unless execution speed
186 <td align=center><b>m</b></td>
187 <td>Used to output the application supplied message associated with
188 the logging event.</td>
192 <td align=center><b>M</b></td>
194 <td>Used to output the method name where the logging request was
197 <p><b>WARNING</b> Generating caller location information is
198 extremely slow and should be avoided unless execution speed
204 <td align=center><b>n</b></td>
206 <td>Outputs the platform dependent line separator character or
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
218 <td align=center><b>p</b></td>
219 <td>Used to output the priority of the logging event.</td>
224 <td align=center><b>r</b></td>
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>
232 <td align=center><b>t</b></td>
234 <td>Used to output the name of the thread that generated the
241 <td align=center><b>x</b></td>
243 <td>Used to output the NDC (nested diagnostic context) associated
244 with the thread that generated the logging event.
250 <td align=center><b>X</b></td>
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>
263 <p>See {@link MDC} class for more details.
270 <td align=center><b>properties</b></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>
285 <td align=center><b>throwable</b></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>
302 <td align=center><b>%</b></td>
304 <td>The sequence %% outputs a single percent sign.
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
315 <p>The optional format modifier are placed between the percent sign
316 and the conversion character.
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.
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.
342 <p>Below are various format modifier examples for the category
343 conversion specifier.
346 <TABLE BORDER=1 CELLPADDING=8>
354 <td align=center>%20c</td>
355 <td align=center>false</td>
356 <td align=center>20</td>
357 <td align=center>none</td>
359 <td>Left pad with spaces if the category name is less than 20
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.
367 <td align=center>%.30c</td>
368 <td align=center>NA</td>
369 <td align=center>none</td>
370 <td align=center>30</td>
372 <td>Truncate from the beginning if the category name is longer than 30
376 <td align=center>%!.30c</td>
377 <td align=center>NA</td>
378 <td align=center>none</td>
379 <td align=center>30</td>
381 <td>Truncate from the end if the category name is longer than 30
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>
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.
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>
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.
406 <p>Below are some examples of conversion patterns.
410 <p><dt><b>%r [%t] %-5p %c %x - %m%n</b>
411 <p><dd>This is essentially the TTCC layout.
413 <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m%n</b>
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
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.
427 @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a>
428 @author Ceki Gülcü
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
436 public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
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";
444 * Initial size of internal buffer, no longer used.
445 * @deprecated since 1.3
447 protected final int BUF_SIZE = 256;
450 * Maximum capacity of internal buffer, no longer used.
451 * @deprecated since 1.3
453 protected final int MAX_CAPACITY = 1024;
456 * Customized pattern conversion rules are stored under this key in the
457 * {@link org.apache.log4j.spi.LoggerRepository LoggerRepository} object store.
459 public static final String PATTERN_RULE_REGISTRY = "PATTERN_RULE_REGISTRY";
463 * Initial converter for pattern.
465 private PatternConverter head;
468 * Conversion pattern.
470 private String conversionPattern;
473 * True if any element in pattern formats information from exceptions.
475 private boolean handlesExceptions;
478 Constructs a EnhancedPatternLayout using the DEFAULT_LAYOUT_PATTERN.
480 The default pattern just produces the application supplied message.
482 public EnhancedPatternLayout() {
483 this(DEFAULT_CONVERSION_PATTERN);
487 * Constructs a EnhancedPatternLayout using the supplied conversion pattern.
488 * @param pattern conversion pattern.
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();
497 handlesExceptions = false;
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.
506 * @param conversionPattern conversion pattern.
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();
515 handlesExceptions = false;
520 * Returns the value of the <b>ConversionPattern</b> option.
521 * @return conversion pattern.
523 public String getConversionPattern() {
524 return conversionPattern;
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.
535 protected org.apache.log4j.helpers.PatternParser createPatternParser(String pattern) {
536 return new org.apache.log4j.pattern.BridgePatternParser(pattern);
541 Activates the conversion pattern. Do not forget to call this method after
542 you change the parameters of the EnhancedPatternLayout instance.
544 public void activateOptions() {
550 * Formats a logging event to a writer.
551 * @param event logging event to be formatted.
553 public String format(final LoggingEvent event) {
554 StringBuffer buf = new StringBuffer();
555 for(PatternConverter c = head;
558 c.format(buf, event);
560 return buf.toString();
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.
568 public boolean ignoresThrowable() {
569 return !handlesExceptions;