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.spi.LoggingEvent;
21 import org.apache.log4j.helpers.PatternParser;
22 import org.apache.log4j.helpers.PatternConverter;
25 // Contributors: Nelson Minar <nelson@monkey.org>
26 // Anders Kristensen <akristensen@dynamicsoft.com>
30 A flexible layout configurable with pattern string.
32 This code is known to have synchronization and other issues
33 which are not present in org.apache.log4j.EnhancedPatternLayout.
34 EnhancedPatternLayout should be used in preference to PatternLayout.
35 EnhancedPatternLayout is distributed in the log4j extras companion.
37 <p>The goal of this class is to {@link #format format} a {@link
38 LoggingEvent} and return the results as a String. The results
39 depend on the <em>conversion pattern</em>.
41 <p>The conversion pattern is closely related to the conversion
42 pattern of the printf function in C. A conversion pattern is
43 composed of literal text and format control expressions called
44 <em>conversion specifiers</em>.
46 <p><i>You are free to insert any literal text within the conversion
49 <p>Each conversion specifier starts with a percent sign (%) and is
50 followed by optional <em>format modifiers</em> and a <em>conversion
51 character</em>. The conversion character specifies the type of
52 data, e.g. category, priority, date, thread name. The format
53 modifiers control such things as field width, padding, left and
54 right justification. The following is a simple example.
56 <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume
57 that the log4j environment was set to use a PatternLayout. Then the
60 Category root = Category.getRoot();
61 root.debug("Message 1");
62 root.warn("Message 2");
64 would yield the output
66 DEBUG [main]: Message 1
67 WARN [main]: Message 2
70 <p>Note that there is no explicit separator between text and
71 conversion specifiers. The pattern parser knows when it has reached
72 the end of a conversion specifier when it reads a conversion
73 character. In the example above the conversion specifier
74 <b>%-5p</b> means the priority of the logging event should be left
75 justified to a width of five characters.
77 The recognized conversion characters are
80 <table border="1" CELLPADDING="8">
81 <th>Conversion Character</th>
85 <td align=center><b>c</b></td>
87 <td>Used to output the category of the logging event. The
88 category conversion specifier can be optionally followed by
89 <em>precision specifier</em>, that is a decimal constant in
92 <p>If a precision specifier is given, then only the corresponding
93 number of right most components of the category name will be
94 printed. By default the category name is printed in full.
96 <p>For example, for the category name "a.b.c" the pattern
97 <b>%c{2}</b> will output "b.c".
103 <td align=center><b>C</b></td>
105 <td>Used to output the fully qualified class name of the caller
106 issuing the logging request. This conversion specifier
107 can be optionally followed by <em>precision specifier</em>, that
108 is a decimal constant in brackets.
110 <p>If a precision specifier is given, then only the corresponding
111 number of right most components of the class name will be
112 printed. By default the class name is output in fully qualified form.
114 <p>For example, for the class name "org.apache.xyz.SomeClass", the
115 pattern <b>%C{1}</b> will output "SomeClass".
117 <p><b>WARNING</b> Generating the caller class information is
118 slow. Thus, use should be avoided unless execution speed is
124 <tr> <td align=center><b>d</b></td> <td>Used to output the date of
125 the logging event. The date conversion specifier may be
126 followed by a <em>date format specifier</em> enclosed between
127 braces. For example, <b>%d{HH:mm:ss,SSS}</b> or
128 <b>%d{dd MMM yyyy HH:mm:ss,SSS}</b>. If no
129 date format specifier is given then ISO8601 format is
132 <p>The date format specifier admits the same syntax as the
133 time pattern string of the {@link
134 java.text.SimpleDateFormat}. Although part of the standard
135 JDK, the performance of <code>SimpleDateFormat</code> is
138 <p>For better results it is recommended to use the log4j date
139 formatters. These can be specified using one of the strings
140 "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link
141 org.apache.log4j.helpers.AbsoluteTimeDateFormat
142 AbsoluteTimeDateFormat}, {@link
143 org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat}
144 and respectively {@link
145 org.apache.log4j.helpers.ISO8601DateFormat
146 ISO8601DateFormat}. For example, <b>%d{ISO8601}</b> or
149 <p>These dedicated date formatters perform significantly
150 better than {@link java.text.SimpleDateFormat}.
155 <td align=center><b>F</b></td>
157 <td>Used to output the file name where the logging request was
160 <p><b>WARNING</b> Generating caller location information is
161 extremely slow and should be avoided unless execution speed
167 <td align=center><b>l</b></td>
169 <td>Used to output location information of the caller which generated
172 <p>The location information depends on the JVM implementation but
173 usually consists of the fully qualified name of the calling
174 method followed by the callers source the file name and line
175 number between parentheses.
177 <p>The location information can be very useful. However, its
178 generation is <em>extremely</em> slow and should be avoided
179 unless execution speed is not an issue.
185 <td align=center><b>L</b></td>
187 <td>Used to output the line number from where the logging request
190 <p><b>WARNING</b> Generating caller location information is
191 extremely slow and should be avoided unless execution speed
198 <td align=center><b>m</b></td>
199 <td>Used to output the application supplied message associated with
200 the logging event.</td>
204 <td align=center><b>M</b></td>
206 <td>Used to output the method name where the logging request was
209 <p><b>WARNING</b> Generating caller location information is
210 extremely slow and should be avoided unless execution speed
216 <td align=center><b>n</b></td>
218 <td>Outputs the platform dependent line separator character or
221 <p>This conversion character offers practically the same
222 performance as using non-portable line separator strings such as
223 "\n", or "\r\n". Thus, it is the preferred way of specifying a
230 <td align=center><b>p</b></td>
231 <td>Used to output the priority of the logging event.</td>
236 <td align=center><b>r</b></td>
238 <td>Used to output the number of milliseconds elapsed from the construction
239 of the layout until the creation of the logging event.</td>
244 <td align=center><b>t</b></td>
246 <td>Used to output the name of the thread that generated the
253 <td align=center><b>x</b></td>
255 <td>Used to output the NDC (nested diagnostic context) associated
256 with the thread that generated the logging event.
262 <td align=center><b>X</b></td>
266 <p>Used to output the MDC (mapped diagnostic context) associated
267 with the thread that generated the logging event. The <b>X</b>
268 conversion character <em>must</em> be followed by the key for the
269 map placed between braces, as in <b>%X{clientNumber}</b> where
270 <code>clientNumber</code> is the key. The value in the MDC
271 corresponding to the key will be output.</p>
273 <p>See {@link MDC} class for more details.
281 <td align=center><b>%</b></td>
283 <td>The sequence %% outputs a single percent sign.
289 <p>By default the relevant information is output as is. However,
290 with the aid of format modifiers it is possible to change the
291 minimum field width, the maximum field width and justification.
293 <p>The optional format modifier is placed between the percent sign
294 and the conversion character.
296 <p>The first optional format modifier is the <em>left justification
297 flag</em> which is just the minus (-) character. Then comes the
298 optional <em>minimum field width</em> modifier. This is a decimal
299 constant that represents the minimum number of characters to
300 output. If the data item requires fewer characters, it is padded on
301 either the left or the right until the minimum width is
302 reached. The default is to pad on the left (right justify) but you
303 can specify right padding with the left justification flag. The
304 padding character is space. If the data item is larger than the
305 minimum field width, the field is expanded to accommodate the
306 data. The value is never truncated.
308 <p>This behavior can be changed using the <em>maximum field
309 width</em> modifier which is designated by a period followed by a
310 decimal constant. If the data item is longer than the maximum
311 field, then the extra characters are removed from the
312 <em>beginning</em> of the data item and not from the end. For
313 example, it the maximum field width is eight and the data item is
314 ten characters long, then the first two characters of the data item
315 are dropped. This behavior deviates from the printf function in C
316 where truncation is done from the end.
318 <p>Below are various format modifier examples for the category
319 conversion specifier.
322 <TABLE BORDER=1 CELLPADDING=8>
330 <td align=center>%20c</td>
331 <td align=center>false</td>
332 <td align=center>20</td>
333 <td align=center>none</td>
335 <td>Left pad with spaces if the category name is less than 20
338 <tr> <td align=center>%-20c</td> <td align=center>true</td> <td
339 align=center>20</td> <td align=center>none</td> <td>Right pad with
340 spaces if the category name is less than 20 characters long.
343 <td align=center>%.30c</td>
344 <td align=center>NA</td>
345 <td align=center>none</td>
346 <td align=center>30</td>
348 <td>Truncate from the beginning if the category name is longer than 30
352 <td align=center>%20.30c</td>
353 <td align=center>false</td>
354 <td align=center>20</td>
355 <td align=center>30</td>
357 <td>Left pad with spaces if the category name is shorter than 20
358 characters. However, if category name is longer than 30 characters,
359 then truncate from the beginning.
362 <td align=center>%-20.30c</td>
363 <td align=center>true</td>
364 <td align=center>20</td>
365 <td align=center>30</td>
367 <td>Right pad with spaces if the category name is shorter than 20
368 characters. However, if category name is longer than 30 characters,
369 then truncate from the beginning.
373 <p>Below are some examples of conversion patterns.
377 <p><dt><b>%r [%t] %-5p %c %x - %m%n</b>
378 <p><dd>This is essentially the TTCC layout.
380 <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m%n</b>
382 <p><dd>Similar to the TTCC layout except that the relative time is
383 right padded if less than 6 digits, thread name is right padded if
384 less than 15 characters and truncated if longer and the category
385 name is left padded if shorter than 30 characters and truncated if
390 <p>The above text is largely inspired from Peter A. Darnell and
391 Philip E. Margolis' highly recommended book "C -- a Software
392 Engineering Approach", ISBN 0-387-97389-3.
394 @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a>
395 @author Ceki Gülcü
399 public class PatternLayout extends Layout {
402 /** Default pattern string for log output. Currently set to the
403 string <b>"%m%n"</b> which just prints the application supplied
405 public final static String DEFAULT_CONVERSION_PATTERN ="%m%n";
407 /** A conversion pattern equivalent to the TTCCCLayout.
408 Current value is <b>%r [%t] %p %c %x - %m%n</b>. */
409 public final static String TTCC_CONVERSION_PATTERN
410 = "%r [%t] %p %c %x - %m%n";
413 protected final int BUF_SIZE = 256;
414 protected final int MAX_CAPACITY = 1024;
417 // output buffer appended to when format() is invoked
418 private StringBuffer sbuf = new StringBuffer(BUF_SIZE);
420 private String pattern;
422 private PatternConverter head;
425 Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.
427 The default pattern just produces the application supplied message.
429 public PatternLayout() {
430 this(DEFAULT_CONVERSION_PATTERN);
434 Constructs a PatternLayout using the supplied conversion pattern.
436 public PatternLayout(String pattern) {
437 this.pattern = pattern;
438 head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN :
443 Set the <b>ConversionPattern</b> option. This is the string which
444 controls formatting and consists of a mix of literal content and
445 conversion specifiers.
448 void setConversionPattern(String conversionPattern) {
449 pattern = conversionPattern;
450 head = createPatternParser(conversionPattern).parse();
454 Returns the value of the <b>ConversionPattern</b> option.
457 String getConversionPattern() {
462 Does not do anything as options become effective
465 void activateOptions() {
470 The PatternLayout does not handle the throwable contained within
471 {@link LoggingEvent LoggingEvents}. Thus, it returns
476 boolean ignoresThrowable() {
481 Returns PatternParser used to parse the conversion string. Subclasses
482 may override this to return a subclass of PatternParser which recognize
483 custom conversion characters.
487 protected PatternParser createPatternParser(String pattern) {
488 return new PatternParser(pattern);
493 Produces a formatted string as specified by the conversion pattern.
495 public String format(LoggingEvent event) {
496 // Reset working stringbuffer
497 if(sbuf.capacity() > MAX_CAPACITY) {
498 sbuf = new StringBuffer(BUF_SIZE);
503 PatternConverter c = head;
506 c.format(sbuf, event);
509 return sbuf.toString();