001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.log4j;
019
020import org.apache.log4j.helpers.OptionConverter;
021import org.apache.log4j.helpers.PatternConverter;
022import org.apache.log4j.pattern.BridgePatternConverter;
023import org.apache.log4j.spi.LoggingEvent;
024
025
026// Contributors:   Nelson Minar <nelson@monkey.org>
027//                 Anders Kristensen <akristensen@dynamicsoft.com>
028
029/**
030 * This class is an enhanced version of org.apache.log4j.PatternLayout
031 * which was originally developed as part of the abandoned log4j 1.3
032 * effort and has been available in the extras companion.
033 * This pattern layout should be used in preference to
034 * org.apache.log4j.PatternLayout except when compatibility
035 * where PatternLayout has been extended either through subclassing
036 * or alternative pattern parsers.
037 *
038 *
039  * <p>A flexible layout configurable with pattern string. The goal of this class
040  * is to {@link #format format} a {@link LoggingEvent} and return the results
041  * in a {@link StringBuffer}. The format of the result depends on the
042  * <em>conversion pattern</em>.
043  * <p>
044  *
045  * <p>The conversion pattern is closely related to the conversion
046  * pattern of the printf function in C. A conversion pattern is
047  * composed of literal text and format control expressions called
048  * <em>conversion specifiers</em>.
049  *
050  * <p><i>Note that you are free to insert any literal text within the
051  * conversion pattern.</i>
052  * </p>
053
054   <p>Each conversion specifier starts with a percent sign (%) and is
055   followed by optional <em>format modifiers</em> and a <em>conversion
056   character</em>. The conversion character specifies the type of
057   data, e.g. category, priority, date, thread name. The format
058   modifiers control such things as field width, padding, left and
059   right justification. The following is a simple example.
060
061   <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume
062   that the log4j environment was set to use a EnhancedPatternLayout. Then the
063   statements
064   <pre>
065   Category root = Category.getRoot();
066   root.debug("Message 1");
067   root.warn("Message 2");
068   </pre>
069   would yield the output
070   <pre>
071   DEBUG [main]: Message 1
072   WARN  [main]: Message 2
073   </pre>
074
075   <p>Note that there is no explicit separator between text and
076   conversion specifiers. The pattern parser knows when it has reached
077   the end of a conversion specifier when it reads a conversion
078   character. In the example above the conversion specifier
079   <b>%-5p</b> means the priority of the logging event should be left
080   justified to a width of five characters.
081
082   The recognized conversion characters are
083
084   <p>
085   <table border="1" CELLPADDING="8">
086   <th>Conversion Character</th>
087   <th>Effect</th>
088
089   <tr>
090     <td align=center><b>c</b></td>
091
092     <td>Used to output the category of the logging event. The
093     category conversion specifier can be optionally followed by
094     NameAbbreviator pattern.
095
096     <p>For example, for the category name "alpha.beta.gamma" the pattern
097     <b>%c{2}</b> will output the last two elements ("beta.gamma"),
098     <b>%c{-2}</b> will remove two elements leaving "gamma",
099     <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&nbsp;MMM&nbsp;yyyy&nbsp;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 and justification.
313
314   <p>The optional format modifier is placed between the percent sign
315   and the conversion character.
316
317   <p>The first optional format modifier is the <em>left justification
318   flag</em> which is just the minus (-) character. Then comes the
319   optional <em>minimum field width</em> modifier. This is a decimal
320   constant that represents the minimum number of characters to
321   output. If the data item requires fewer characters, it is padded on
322   either the left or the right until the minimum width is
323   reached. The default is to pad on the left (right justify) but you
324   can specify right padding with the left justification flag. The
325   padding character is space. If the data item is larger than the
326   minimum field width, the field is expanded to accommodate the
327   data. The value is never truncated.
328
329   <p>This behavior can be changed using the <em>maximum field
330   width</em> modifier which is designated by a period followed by a
331   decimal constant. If the data item is longer than the maximum
332   field, then the extra characters are removed from the
333   <em>beginning</em> of the data item and not from the end. For
334   example, it the maximum field width is eight and the data item is
335   ten characters long, then the first two characters of the data item
336   are dropped. This behavior deviates from the printf function in C
337   where truncation is done from the end.
338
339   <p>Below are various format modifier examples for the category
340   conversion specifier.
341
342   <p>
343   <TABLE BORDER=1 CELLPADDING=8>
344   <th>Format modifier
345   <th>left justify
346   <th>minimum width
347   <th>maximum width
348   <th>comment
349
350   <tr>
351   <td align=center>%20c</td>
352   <td align=center>false</td>
353   <td align=center>20</td>
354   <td align=center>none</td>
355
356   <td>Left pad with spaces if the category name is less than 20
357   characters long.
358
359   <tr> <td align=center>%-20c</td> <td align=center>true</td> <td
360   align=center>20</td> <td align=center>none</td> <td>Right pad with
361   spaces if the category name is less than 20 characters long.
362
363   <tr>
364   <td align=center>%.30c</td>
365   <td align=center>NA</td>
366   <td align=center>none</td>
367   <td align=center>30</td>
368
369   <td>Truncate from the beginning if the category name is longer than 30
370   characters.
371
372   <tr>
373   <td align=center>%20.30c</td>
374   <td align=center>false</td>
375   <td align=center>20</td>
376   <td align=center>30</td>
377
378   <td>Left pad with spaces if the category name is shorter than 20
379   characters. However, if category name is longer than 30 characters,
380   then truncate from the beginning.
381
382   <tr>
383   <td align=center>%-20.30c</td>
384   <td align=center>true</td>
385   <td align=center>20</td>
386   <td align=center>30</td>
387
388   <td>Right pad with spaces if the category name is shorter than 20
389   characters. However, if category name is longer than 30 characters,
390   then truncate from the beginning.
391
392   </table>
393
394   <p>Below are some examples of conversion patterns.
395
396   <dl>
397
398   <p><dt><b>%r [%t] %-5p %c %x - %m%n</b>
399   <p><dd>This is essentially the TTCC layout.
400
401   <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m%n</b>
402
403   <p><dd>Similar to the TTCC layout except that the relative time is
404   right padded if less than 6 digits, thread name is right padded if
405   less than 15 characters and truncated if longer and the category
406   name is left padded if shorter than 30 characters and truncated if
407   longer.
408
409  </dl>
410
411   <p>The above text is largely inspired from Peter A. Darnell and
412   Philip E. Margolis' highly recommended book "C -- a Software
413   Engineering Approach", ISBN 0-387-97389-3.
414
415   @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a>
416   @author Ceki G&uuml;lc&uuml;
417
418
419   @since 1.2.16 */
420public class EnhancedPatternLayout extends Layout {
421  /** Default pattern string for log output. Currently set to the
422      string <b>"%m%n"</b> which just prints the application supplied
423      message. */
424  public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
425
426  /** A conversion pattern equivalent to the TTCCCLayout.
427      Current value is <b>%r [%t] %p %c %x - %m%n</b>. */
428  public static final String TTCC_CONVERSION_PATTERN =
429    "%r [%t] %p %c %x - %m%n";
430
431    /**
432     * Initial size of internal buffer, no longer used.
433     * @deprecated since 1.3
434     */
435  protected final int BUF_SIZE = 256;
436
437    /**
438     * Maximum capacity of internal buffer, no longer used.
439     * @deprecated since 1.3
440     */
441  protected final int MAX_CAPACITY = 1024;
442
443  /**
444   * Customized pattern conversion rules are stored under this key in the
445   * {@link org.apache.log4j.spi.LoggerRepository LoggerRepository} object store.
446   */
447  public static final String PATTERN_RULE_REGISTRY = "PATTERN_RULE_REGISTRY";
448
449
450  /**
451    *  Initial converter for pattern.
452    */
453  private PatternConverter head;
454
455  /**
456   * Conversion pattern.
457   */
458  private String conversionPattern;
459
460  /**
461   * True if any element in pattern formats information from exceptions.
462   */
463  private boolean handlesExceptions;
464
465  /**
466     Constructs a EnhancedPatternLayout using the DEFAULT_LAYOUT_PATTERN.
467
468     The default pattern just produces the application supplied message.
469  */
470  public EnhancedPatternLayout() {
471    this(DEFAULT_CONVERSION_PATTERN);
472  }
473
474  /**
475    * Constructs a EnhancedPatternLayout using the supplied conversion pattern.
476   * @param pattern conversion pattern.
477  */
478  public EnhancedPatternLayout(final String pattern) {
479    this.conversionPattern = pattern;
480    head = createPatternParser(
481            (pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse();
482    if (head instanceof BridgePatternConverter) {
483        handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable();
484    } else {
485        handlesExceptions = false;
486    }
487  }
488
489  /**
490   * Set the <b>ConversionPattern</b> option. This is the string which
491   * controls formatting and consists of a mix of literal content and
492   * conversion specifiers.
493   *
494   * @param conversionPattern conversion pattern.
495  */
496  public void setConversionPattern(final String conversionPattern) {
497    this.conversionPattern =
498      OptionConverter.convertSpecialChars(conversionPattern);
499      head = createPatternParser(this.conversionPattern).parse();
500      if (head instanceof BridgePatternConverter) {
501          handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable();
502      } else {
503          handlesExceptions = false;
504      }
505  }
506
507  /**
508   *  Returns the value of the <b>ConversionPattern</b> option.
509   * @return conversion pattern.
510   */
511  public String getConversionPattern() {
512    return conversionPattern;
513  }
514
515
516    /**
517      Returns PatternParser used to parse the conversion string. Subclasses
518      may override this to return a subclass of PatternParser which recognize
519      custom conversion characters.
520
521      @since 0.9.0
522    */
523    protected org.apache.log4j.helpers.PatternParser createPatternParser(String pattern) {
524      return new org.apache.log4j.pattern.BridgePatternParser(pattern);
525    }
526
527
528  /**
529    Activates the conversion pattern. Do not forget to call this method after
530    you change the parameters of the EnhancedPatternLayout instance.
531  */
532  public void activateOptions() {
533      // nothing to do.
534  }
535
536
537  /**
538   *  Formats a logging event to a writer.
539   * @param event logging event to be formatted.
540  */
541  public String format(final LoggingEvent event) {
542      StringBuffer buf = new StringBuffer();
543      for(PatternConverter c = head;
544          c != null;
545          c = c.next) {
546          c.format(buf, event);
547      }
548      return buf.toString();
549  }
550
551  /**
552   * Will return false if any of the conversion specifiers in the pattern
553   * handles {@link Exception Exceptions}.
554   * @return true if the pattern formats any information from exceptions.
555   */
556  public boolean ignoresThrowable() {
557    return !handlesExceptions;
558  }
559}