Debian Codegraph @

logback-site/src/site/pages/manual/layouts.html

raw
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 <html xmlns="http://www.w3.org/1999/xhtml">
5 <head>
6 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
7 <title>Chapter 6: Layouts</title>
8 <link rel="stylesheet" type="text/css" href="../css/common.css" />
9 <link rel="stylesheet" type="text/css" href="../css/screen.css" media="screen" />
10 <link rel="stylesheet" type="text/css" href="../css/_print.css" media="print" />
11 <link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen" />
12
13 </head>
14 <body onload="prettyPrint(); decorate();">
15 <script type="text/javascript">prefix='../';</script>
16 <script type="text/javascript" src="../js/prettify.js"></script>
17 <script type="text/javascript" src="../templates/header.js"></script>
18 <script type="text/javascript" src="../js/dsl.js"></script>
19 <script type="text/javascript" src="../js/jquery-min.js"></script>
20 <script type="text/javascript" src="../js/decorator.js"></script>
21
22 <div id="left">
23 <noscript>Please turn on Javascript to view this menu</noscript>
24 <script src="../templates/left.js" type="text/javascript"></script>
25 </div>
26 <div id="right">
27 <script src="menu.js" type="text/javascript"></script>
28 </div>
29 <div id="content">
30
31 <h1>Chapter 6: Layouts</h1>
32
33 <a href="layouts_ja.html">&#x548C;&#x8A33; (Japanese translation)</a>
34
35 <div class="quote">
36 <p>TCP implementations will follow a general principle of
37 robustness: be conservative in what you do, be liberal in what
38 you accept from others.
39 </p>
40 <p>&mdash;JON POSTEL, RFC 793</p>
41 </div>
42
43 <script src="../templates/creative.js" type="text/javascript"></script>
44 <script src="../templates/setup.js" type="text/javascript"></script>
45
46 <h2 class="doAnchor">What is a layout?</h2>
47
48 <p>In case you were wondering, layouts have nothing to do with
49 large estates in Florida. Layouts are logback components
50 responsible for transforming an incoming event into a String. The
51 <code>format()</code> method in the <a
52 href="../xref/ch/qos/logback/core/Layout.html"><code>Layout</code></a>
53 interface takes an object that represents an event (of any type)
54 and returns a String. A synopsis of the <code>Layout</code>
55 interface is shown below.
56 </p>
57
58 <pre class="prettyprint source">public interface Layout&lt;E> extends ContextAware, LifeCycle {
59
60 String doLayout(E event);
61 String getFileHeader();
62 String getPresentationHeader();
63 String getFileFooter();
64 String getPresentationFooter();
65 String getContentType();
66 }</pre>
67
68 <p>This interface is rather simple and yet is sufficient for many
69 formatting needs. The Texan developer from Texas, whom you might
70 know from Joseph Heller's <em>Catch-22</em>, might exclaim: it
71 just takes five methods to implement a layout!!?
72 </p>
73
74 <h2>Logback-classic</h2>
75
76 <p>Logback-classic is wired to process only events of type
77 <a href="../xref/ch/qos/logback/classic/spi/ILoggingEvent.html">
78 <code>ch.qos.logback.classic.spi.ILoggingEvent</code></a>. This
79 fact will be apparent throughout this section.</p>
80
81 <h2 class="doAnchor" name="writingYourOwnLayout">Writing your own
82 custom Layout</h2>
83
84 <p>Let us implement a simple yet functional layout for the
85 logback-classic module that prints the time elapsed since the
86 start of the application, the level of the logging event, the
87 caller thread between brackets, its logger name, a dash followed
88 by the event message and a new line.
89 </p>
90
91 <p>Sample output might look like:</p>
92
93 <div class="source">10489 DEBUG [main] com.marsupial.Pouch - Hello world.</div>
94
95 <p>Here is a possible implementation, authored by the Texan developer:</p>
96 <em>Example: Sample implementation of a Layout
97 <a href="../xref/chapters/layouts/MySampleLayout.html">
98 (logback-examples/src/main/java/chapters/layouts/MySampleLayout.java)</a></em>
99
100 <pre class="prettyprint source">package chapters.layouts;
101
102 import ch.qos.logback.classic.spi.ILoggingEvent;
103 import ch.qos.logback.core.LayoutBase;
104
105 public class MySampleLayout extends LayoutBase&lt;ILoggingEvent> {
106
107 public String doLayout(ILoggingEvent event) {
108 StringBuffer sbuf = new StringBuffer(128);
109 sbuf.append(event.getTimeStamp() - event.getLoggingContextVO.getBirthTime());
110 sbuf.append(" ");
111 sbuf.append(event.getLevel());
112 sbuf.append(" [");
113 sbuf.append(event.getThreadName());
114 sbuf.append("] ");
115 sbuf.append(event.getLoggerName();
116 sbuf.append(" - ");
117 sbuf.append(event.getFormattedMessage());
118 sbuf.append(CoreConstants.LINE_SEP);
119 return sbuf.toString();
120 }
121 }</pre>
122
123 <p>Note that <code>MySampleLayout</code> extends <a
124 href="../xref/ch/qos/logback/core/LayoutBase.html">
125 <code>LayoutBase</code></a>. This class manages state common to
126 all layout instances, such as whether the layout is started or
127 stopped, header, footer and content type data. It allows the
128 developer to concentrate on the formatting expected from his/her
129 <code>Layout</code>. Note that the <code>LayoutBase</code> class
130 is generic. In its class declaration, <code>MySampleLayout</code>
131 extends <code>LayoutBase&lt;ILoggingEvent&gt;</code>.
132 </p>
133
134 <p>The <code>doLayout(ILoggingEvent event)</code> method, i.e. the
135 only method in <code>MySampleLayout</code>, begins by
136 instantiating a <code>StringBuffer</code>. It proceeds by adding
137 various fields of the event parameter. The Texan from Texas was
138 careful to print the formatted form of the message. This is
139 significant if one or more parameters were passed along with
140 the logging request.
141 </p>
142
143 <p>After adding these various characters to the string buffer, the
144 <code>doLayout()</code> method converts the buffer into a
145 <code>String</code> and returns the resulting value.
146 </p>
147
148 <p>In the above example, the <code>doLayout</code> method ignores
149 any eventual exceptions contained in the event. In a real world
150 layout implementation, you would most probably want to print the
151 contents of exceptions as well.
152 </p>
153
154 <h3 class="doAnchor" name="configuringYourOwnLayout">Configuring
155 your custom layout</h3>
156
157 <p>Custom layouts are configured as any other component. As
158 mentioned earlier, <code>FileAppender</code> and its sub-classes
159 expect an encoder. In order to fulfill this requirement, we pass
160 to <code>FileAppender</code> an instance of
161 <code>LayoutWrappingEncoder</code> which wraps our
162 <code>MySampleLayout</code>. Here is the configuration file:</p>
163
164 <em>Example: Configuration of MySampleLayout
165 (logback-examples/src/main/resources/chapters/layouts/sampleLayoutConfig.xml)</em>
166 <span class="asGroovy" onclick="return asGroovy('sampleLayoutConfig');">View as .groovy</span>
167 <pre id="sampleLayoutConfig" class="prettyprint source">&lt;configuration>
168
169 &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
170 <b>&lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"></b>
171 <b>&lt;layout class="chapters.layouts.MySampleLayout" /></b>
172 <b>&lt;/encoder></b>
173 &lt;/appender>
174
175 &lt;root level="DEBUG">
176 &lt;appender-ref ref="STDOUT" />
177 &lt;/root>
178 &lt;/configuration></pre>
179
180 <p>The sample application <a
181 href="../xref/chapters/layouts/SampleLogging.html">
182 <code>chapters.layouts.SampleLogging</code></a> configures logback
183 with the configuration script passed as its first argument and
184 then logs a debug message, followed by an error message. </p>
185
186 <p>To run this example issue the following command from within the
187 <em>logback-examples</em> directory.
188 </p>
189
190 <p class="command">java chapters.layouts.SampleLogging src/main/java/chapters/layouts/sampleLayoutConfig.xml</p>
191
192 <p> This will produce:</p>
193
194 <div class="source"><pre>0 DEBUG [main] chapters.layouts.SampleLogging - Everything's going well
195 0 ERROR [main] chapters.layouts.SampleLogging - maybe not quite...</pre></div>
196
197 <p>That was simple enough. The skeptic Pyrrho of Elea, who
198 insists that nothing is certain except perhaps uncertainty itself,
199 which is by no means certain either, might ask: how about a layout
200 with options? The reader shall find a slightly modified version
201 of our custom layout in <a
202 href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2.java</code></a>. As
203 mentioned throughout this manual, adding a property to a layout or
204 any other logback component is as simple as declaring a setter
205 method for the property.
206 </p>
207
208 <p>The <a
209 href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2</code></a>
210 class contains two properties. The first one is a prefix that can
211 be added to the output. The second property is used to choose
212 whether to display the name of the thread from which the logging
213 request was sent.
214 </p>
215
216 <p>Here is a copy of the <a
217 href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2</code></a>
218 class :</p>
219
220 <pre class="prettyprint source">package chapters.layouts;
221
222 import ch.qos.logback.classic.spi.ILoggingEvent;
223 import ch.qos.logback.core.LayoutBase;
224
225 public class MySampleLayout2 extends LayoutBase&lt;ILoggingEvent> {
226
227 String prefix = null;
228 boolean printThreadName = true;
229
230 <b>public void setPrefix(String prefix) {
231 this.prefix = prefix;
232 }
233
234 public void setPrintThreadName(boolean printThreadName) {
235 this.printThreadName = printThreadName;
236 }</b>
237
238 public String doLayout(ILoggingEvent event) {
239 StringBuffer sbuf = new StringBuffer(128);
240 <b>if (prefix != null) {
241 sbuf.append(prefix + ": ");
242 }</b>
243 sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime());
244 sbuf.append(" ");
245 sbuf.append(event.getLevel());
246 <b>if (printThreadName) {
247 sbuf.append(" [");
248 sbuf.append(event.getThreadName());
249 sbuf.append("] ");
250 } else {
251 sbuf.append(" ");
252 }</b>
253 sbuf.append(event.getLoggerName());
254 sbuf.append(" - ");
255 sbuf.append(event.getFormattedMessage());
256 sbuf.append(LINE_SEP);
257 return sbuf.toString();
258 }
259 }</pre>
260
261
262 <p>The addition of the corresponding setter method is all that is
263 needed to enable the configuration of a property. Note that the
264 <code>PrintThreadName</code> property is a boolean and not a
265 <code>String</code>. Configuration of logback components was
266 covered in detail in the <a
267 href="configuration.html">chapter on configuration</a>. The <a
268 href="onJoran.html">chapter on Joran</a> provides further detail. Here is
269 the configuration file tailor made for
270 <code>MySampleLayout2</code>.
271 </p>
272
273
274 <span class="asGroovy" onclick="return asGroovy('MySampleLayout2');">View as .groovy</span>
275 <pre id="MySampleLayout2" class="prettyprint source">&lt;configuration>
276
277 &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
278 &lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
279 &lt;layout class="chapters.layouts.MySampleLayout2">
280 <b>&lt;prefix&gt;MyPrefix&lt;/prefix&gt;</b>
281 <b>&lt;printThreadName&gt;false&lt;/printThreadName&gt;</b>
282 &lt;/layout>
283 &lt;/encoder>
284 &lt;/appender>
285
286 &lt;root level="DEBUG">
287 &lt;appender-ref ref="STDOUT" />
288 &lt;/root>
289 &lt;/configuration></pre>
290
291 <p></p>
292
293
294 <h2 class="doAnchor" name="ClassicPatternLayout">PatternLayout</h2>
295
296 <p>Logback classic ships with a flexible layout called <a
297 href="../xref/ch/qos/logback/classic/PatternLayout.html">
298 <code>PatternLayout</code></a>. As all layouts,
299 <code>PatternLayout</code> takes a logging event and returns a
300 <code>String</code>. However, this <code>String</code> can be
301 customized by tweaking <code>PatternLayout</code>'s
302 conversion pattern.
303 </p>
304
305 <p>The conversion pattern of <code>PatternLayout</code> is closely
306 related to the conversion pattern of the <code>printf()</code>
307 function in the C programming language. A conversion pattern is
308 composed of literal text and format control expressions called
309 <em>conversion specifiers</em>. You are free to insert any literal
310 text within the conversion pattern. Each conversion specifier
311 starts with a percent sign '%' and is followed by optional
312 <em>format modifiers</em>, a <em>conversion word</em> and optional
313 parameters between braces. The conversion word controls the data
314 field to convert, e.g. logger name, level, date or thread
315 name. The format modifiers control field width, padding, and left
316 or right justification.
317 </p>
318
319 <p>As already mentioned on several occasions,
320 <code>FileAppender</code> and sub-classes expect an
321 encoder. Consequently, when used in conjunction with
322 <code>FileAppender</code> or its subclasses a
323 <code>PatternLayout</code> must be wrapped within an
324 encoder. Given that the
325 <code>FileAppender</code>/<code>PatternLayout</code> combination
326 is so common, logback ships with an encoder named
327 <code>PatternLayoutEncoder</code>, designed solely for the purpose
328 of wrapping a <code>PatternLayout</code> instance so that it can
329 be seen as encoder. Below is an example which programmatically
330 configures a <code>ConsoleAppender</code> with a
331 <code>PatternLayoutEncoder</code>:</p>
332
333
334 <em>
335 Example: Sample usage of a PatternLayout
336 <a href="../xref/chapters/layouts/PatternSample.html">
337 (logback-examples/src/main/java/chapters/layouts/PatternSample.java)</a>
338 </em>
339 <pre class="prettyprint source">package chapters.layouts;
340
341 import org.slf4j.LoggerFactory;
342
343 import ch.qos.logback.classic.Logger;
344 import ch.qos.logback.classic.LoggerContext;
345 import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
346 import ch.qos.logback.classic.spi.ILoggingEvent;
347 import ch.qos.logback.core.ConsoleAppender;
348
349 public class PatternSample {
350
351 static public void main(String[] args) throws Exception {
352 Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
353 LoggerContext loggerContext = rootLogger.getLoggerContext();
354 // we are not interested in auto-configuration
355 loggerContext.reset();
356
357 <b>PatternLayoutEncoder encoder = new PatternLayoutEncoder();</b>
358 <b>encoder.setContext(loggerContext);</b>
359 <b>encoder.setPattern("%-5level [%thread]: %message%n");</b>
360 <b>encoder.start();</b>
361
362 ConsoleAppender&lt;ILoggingEvent> appender = new ConsoleAppender&lt;ILoggingEvent>();
363 appender.setContext(loggerContext);
364 appender.setEncoder(encoder);
365 appender.start();
366
367 rootLogger.addAppender(appender);
368
369 rootLogger.debug("Message 1");
370 rootLogger.warn("Message 2");
371 }
372 }</pre>
373
374 <p>In the above example, the conversion pattern is set to be
375 <b>"%-5level [%thread]: %message%n"</b>. A synopsis of conversion
376 word included in logback will be given shortly. Running
377 <code>PatternSample</code> application as:
378 </p>
379
380 <p class="source">java java chapters.layouts.PatternSample</p>
381
382 <p>will yield the following output on the console.</p>
383
384 <p class="source">DEBUG [main]: Message 1
385 WARN [main]: Message 2</p>
386
387 <p>Note that in the conversion pattern <b>"%-5level [%thread]:
388 %message%n"</b> there is no explicit separator between literal
389 text and conversion specifiers. When parsing a conversion pattern,
390 <code>PatternLayout</code> is capable of differentiating between
391 literal text (space characters, the brackets, colon character) and
392 conversion specifiers. In the example above, the conversion
393 specifier %-5level means the level of the logging event should be
394 left justified to a width of five characters. Format specifiers
395 will be explained below.
396 </p>
397
398 <p>In <code>PatternLayout</code>, parenthesis can be used to group
399 conversion patterns. <b>It follows that the '(' and ')' carry
400 special meaning and need to be escaped if intended to be used as
401 literals. </b> The special nature of parenthesis is further <a
402 href="#Parentheses">explained below</a>.
403 </p>
404
405 <p>As mentioned previously, certain conversion specifiers may
406 include optional parameters passed between braces. A sample
407 conversion specifier with options could be
408 <code>%logger{10}</code>. Here "logger" is the conversion word,
409 and 10 is the option. Options are <a href="#cwOptions">further
410 discussed below</a>.
411 </p>
412
413 <p>The recognized conversions words along with their options are
414 described in the table below. When multiple conversion words are
415 listed in the same table cell, they are considered as aliases.
416 </p>
417
418 <table class="bodyTable properties striped" border="0">
419 <tr>
420 <th><a name="conversionWord" href="#conversionWord">Conversion Word</a></th>
421 <th>Effect</th>
422 </tr>
423
424 <tr>
425 <td class="word" name="logger">
426 <a name="logger" href="#logger"><span class="anchor"/></a>
427 <b>c</b>{<em>length</em>} <br />
428 <b>lo</b>{<em>length</em>} <br />
429 <b>logger</b>{<em>length</em>} <br />
430 </td>
431
432 <td>
433 Outputs the name of the logger at the origin of the logging
434 event.
435
436 <p>This conversion word takes an integer as its first and
437 only option. The converter's abbreviation algorithm will
438 shorten the logger name, usually without significant loss of
439 meaning. Setting the value of length option to zero
440 constitutes an exception. It will cause the conversion word
441 to return the sub-string right to the rightmost dot
442 character in the logger name. The next table provides
443 examples of the abbreviation algorithm in action.
444 </p>
445
446 <table class="bodyTable dark" border="0" cellpadding="8">
447 <tr>
448 <th>Conversion specifier</th>
449 <th>Logger name</th>
450 <th>Result</th>
451 </tr>
452 <tr>
453 <td>%logger</td>
454 <td>mainPackage.sub.sample.Bar</td>
455 <td>mainPackage.sub.sample.Bar</td>
456 </tr>
457
458 <tr>
459 <td>%logger{0}</td>
460 <td>mainPackage.sub.sample.Bar</td>
461 <td>Bar</td>
462 </tr>
463
464 <tr>
465 <td>%logger{5}</td>
466 <td>mainPackage.sub.sample.Bar</td>
467 <td>m.s.s.Bar</td>
468 </tr>
469
470 <tr>
471 <td>%logger{10}</td>
472 <td>mainPackage.sub.sample.Bar</td>
473 <td>m.s.s.Bar</td>
474 </tr>
475
476 <tr>
477 <td>%logger{15}</td>
478 <td>mainPackage.sub.sample.Bar</td>
479 <td>m.s.sample.Bar</td>
480 </tr>
481
482 <tr>
483 <td>%logger{16}</td>
484 <td>mainPackage.sub.sample.Bar</td>
485 <td>m.sub.sample.Bar</td>
486 </tr>
487
488 <tr>
489 <td>%logger{26}</td>
490 <td>mainPackage.sub.sample.Bar</td>
491 <td>mainPackage.sub.sample.Bar</td>
492 </tr>
493 </table>
494
495 <p>Please note that the rightmost segment in a logger name
496 is never abbreviated, even if its length is longer than the
497 <em>length</em> option. Other segments may be shortened to
498 at most a single character but are never removed.</p>
499
500 </td>
501 </tr>
502
503 <tr>
504 <td class="word" name="class">
505 <b>C</b>{<em>length</em>} <br />
506 <b>class</b>{<em>length</em>} <br />
507 </td>
508
509 <td>
510 <p>Outputs the fully-qualified class name of the caller
511 issuing the logging request.
512 </p>
513
514 <p>Just like the <em>%logger</em> conversion word above,
515 this conversion takes an integer as an option to shorten
516 the class name. Zero carries special meaning and will cause
517 the simple class name to be printed without the package name
518 prefix. By default the class name is printed in full.
519 </p>
520
521 <p>Generating the caller class information is not
522 particularly fast. Thus, its use should be avoided unless
523 execution speed is not an issue.
524 </p>
525 </td>
526 </tr>
527
528 <tr>
529 <td class="word" name="contextName">
530 <b>contextName</b><br/>
531 <b>cn</b><br/></td>
532 <td>Outputs the name of the logger context to which the
533 logger at the origin of the event was attached to. </td>
534 </tr>
535 <tr>
536 <td class="word" name="date">
537 <b>d</b>{<em>pattern</em>} <br />
538 <b>date</b>{<em>pattern</em>} <br />
539 <b>d</b>{<em>pattern</em>, <em>timezone</em>} <br />
540 <b>date</b>{<em>pattern</em>,&nbsp;<em>timezone</em>} <br />
541 </td>
542 <td>
543 <p>Used to output the date of the logging event. The date
544 conversion word admits a pattern string as a parameter. The
545 pattern syntax is compatible with the format accepted by <a
546 href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html"><code>java.text.SimpleDateFormat</code></a>.</p>
547
548 <p>You can specify the string <em>"ISO8601"</em> for the
549 ISO8601 date format. Note that the %date conversion word
550 defaults to the <a
551 href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601 date
552 format</a> in the absence of a pattern parameter.</p>
553
554 <p>Here are some sample parameter values. They assume that
555 the actual date is Friday 20th of October, 2006 and that the
556 author has returned to working on this document just after
557 lunch.</p>
558
559 <table class="bodyTable dark" cellpadding="8">
560 <tr>
561 <th>Conversion Pattern</th>
562 <th>Result</th>
563 </tr>
564 <tr>
565 <td>%d</td>
566 <td>2006-10-20 14:06:49,812</td>
567 </tr>
568 <tr>
569 <td>%date</td>
570 <td>2006-10-20 14:06:49,812</td>
571 </tr>
572 <tr>
573 <td>%date{ISO8601}</td>
574 <td>2006-10-20 14:06:49,812</td>
575 </tr>
576 <tr>
577 <td>%date{HH:mm:ss.SSS}</td>
578 <td>14:06:49.812</td>
579 </tr>
580 <tr>
581 <td>%date{dd&nbsp;MMM&nbsp;yyyy;HH:mm:ss.SSS}</td>
582 <td>20 oct. 2006;14:06:49.812 </td>
583 </tr>
584 </table>
585
586 <p>The second parameter specifies a timezone. For example,
587 the '%date{HH:mm:ss.SSS,&nbsp;Australia/Perth} would print
588 the time in the time zone of Perth, Australia, the world's
589 most isolated city. Note that in the absence of the
590 timezone parameter, the default timezone of the host Java
591 platform is used. If the specified timezone identifier is
592 unknown or misspelled, the GMT timezone is assumed as
593 dictated by the <a
594 href="http://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone(java.lang.String)">TimeZone.getTimeZone(String)</a>
595 method specification.
596 </p>
597
598 <p><span class="label">common error</span> Given that the
599 comma ',' character is interpreted as the parameter
600 separator, the pattern <code>HH:mm:ss,SSS</code> will be
601 interpreted as the pattern <code>HM:mm:ss</code> and the
602 timezone <code>SSS</code>. If you wish to include a comma in
603 your date pattern, then simply enclose the pattern between
604 quotes. For example, %date{<b>"</b>HH:mm:ss,SSS<b>"</b>}.
605 </p>
606 </td>
607 </tr>
608
609 <tr>
610 <td class="word" name="file">
611 <b>F / file</b>
612 </td>
613
614 <td>
615 <p>Outputs the file name of the Java source file where the
616 logging request was issued.
617 </p>
618
619 <p>Generating the file information is not particularly fast.
620 Thus, its use should be avoided unless execution speed is
621 not an issue.
622 </p>
623 </td>
624 </tr>
625
626 <tr >
627 <td class="word" name="caller">
628 <b>caller{depth}</b>
629 <b>caller{depthStart..depthEnd}</b>
630 <b>caller{depth, evaluator-1, ... evaluator-n}</b>
631 <b>caller{depthStart..depthEnd, evaluator-1, ... evaluator-n}</b>
632 </td>
633
634 <td>
635 <p>Outputs location information of the caller which
636 generated the logging event.
637 </p>
638
639 <p>The location information depends on the JVM
640 implementation but usually consists of the fully qualified
641 name of the calling method followed by the caller's source,
642 the file name and line number between parentheses.
643 </p>
644
645 <p>A integer can be added to the <em>caller</em> conversion
646 specifier's options to configure the depth of the
647 information to be displayed.
648 </p>
649
650 <p>For example, <b>%caller{2}</b> would display the
651 following excerpt:</p>
652
653 <pre class="source white_bg">0 [main] DEBUG - logging statement
654 Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)
655 Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)</pre>
656
657 <p>And <b>%caller{3}</b> would display this other excerpt:</p>
658
659 <pre class="source white_bg">16 [main] DEBUG - logging statement
660 Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)
661 Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)
662 Caller+2 at mainPackage.ConfigTester.main(ConfigTester.java:38)</pre>
663
664 <p>A range specifier can be added to the <em>caller</em> conversion specifier's
665 options to configure the depth range of the information to be displayed.
666 </p>
667
668 <p>For example, <b>%caller{1..2}</b> would display the following excerpt:</p>
669
670 <pre class="source white_bg">0 [main] DEBUG - logging statement
671 Caller+0 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)</pre>
672
673 <p>This conversion word can also use evaluators to test
674 logging events against a given criterion before computing
675 caller data. For example, using <b>%caller{3,
676 CALLER_DISPLAY_EVAL}</b> will display three lines of
677 stacktrace, only if the evaluator called
678 <em>CALLER_DISPLAY_EVAL</em> returns a <b>positive</b>
679 answer.
680 </p>
681
682 <p>Evaluators are described below.</p>
683 </td>
684 </tr>
685
686 <tr>
687 <td class="word" name="line">
688 <b>L / line</b>
689 </td>
690
691 <td><p>Outputs the line number from where the logging
692 request was issued.</p>
693
694 <p>Generating the line number information is not
695 particularly fast. Thus, its use should be avoided unless
696 execution speed is not an issue.
697 </p>
698 </td>
699 </tr>
700
701
702 <tr>
703 <td class="word" name="message">
704 <b>m / msg / message</b>
705 </td>
706 <td>
707 <p>Outputs the application-supplied message associated with
708 the logging event.
709 </p>
710 </td>
711 </tr>
712
713 <tr>
714 <td class="word" name="method">
715 <b>M / method</b>
716 </td>
717
718 <td>
719 <p>Outputs the method name where the logging request was
720 issued.</p>
721 <p>Generating the method name is not particularly fast.
722 Thus, its use should be avoided unless execution speed is
723 not an issue.</p>
724 </td>
725 </tr>
726
727 <tr>
728 <td class="word" name="newline">
729 <b>n</b>
730 </td>
731
732 <td>
733 <p>Outputs the platform dependent line separator
734 character or characters.</p>
735 <p>This conversion word offers practically the same
736 performance as using non-portable line separator strings
737 such as "\n", or "\r\n". Thus, it is the preferred way of
738 specifying a line separator.
739 </p>
740 </td>
741
742 </tr>
743
744 <tr>
745 <td class="word" name="level">
746 <b>p / le / level</b>
747 </td>
748 <td>Outputs the level of the logging event.</td>
749 </tr>
750
751 <tr>
752
753 <td class="word" name="relative">
754 <b>r / relative</b>
755 </td>
756
757 <td>Outputs the number of milliseconds elapsed since the start
758 of the application until the creation of the logging event.
759 </td>
760 </tr>
761
762
763 <tr>
764 <td class="word" name="relative">
765 <b>t / thread</b>
766 </td>
767
768 <td>Outputs the name of the thread that generated the logging
769 event.
770 </td>
771
772 </tr>
773
774 <tr>
775 <td class="word" name="mdc">
776 <b>X</b>{<em>key:-defaultVal</em>} <br />
777 <b>mdc</b>{<em>key:-defaultVal</em>} <br />
778 </td>
779
780 <td>
781
782 <p>Outputs the MDC (mapped diagnostic context) associated
783 with the thread that generated the logging event.
784 </p>
785
786 <p>If the <b>mdc</b> conversion word is followed by a key
787 between braces, as in <b>%mdc{userid}</b>, then the MDC
788 value corresponding to the key 'userid' will be output. If
789 the value is null, then the <a
790 href="configuration.html#defaultValuesForVariables">default
791 value</a> specified after the <b>:-</b> operator is
792 output. If no default value is specified than the empty
793 string is output.
794 </p>
795
796 <p>If no key is given, then the entire content of the MDC
797 will be output in the format "key1=val1, key2=val2".
798 </p>
799
800 <p>See the <a href="mdc.html">chapter on MDC</a> for more
801 details on the subject.</p>
802
803 </td>
804 </tr>
805 <tr>
806 <td class="word" name="ex">
807 <b>ex</b>{<em>depth</em>} <br />
808 <b>exception</b>{<em>depth</em>} <br />
809 <b>throwable</b>{<em>depth</em>} <br />
810 <br />
811 <b>ex</b>{depth, evaluator-1, ..., evaluator-n} <br />
812 <b>exception</b>{depth, evaluator-1, ..., evaluator-n} <br />
813 <b>throwable</b>{depth, evaluator-1, ..., evaluator-n}
814 </td>
815
816 <td>
817 <p>Outputs the stack trace of the exception
818 associated with the logging event, if any. By default the
819 full stack trace will be output.
820 </p>
821
822
823 <p>The <em>throwable</em> conversion word can followed by one of
824 the following options:
825 </p>
826 <ul>
827 <li><em>short</em>: prints the first line of the stack trace</li>
828 <li><em>full</em>: prints the full stack trace</li>
829 <li>Any integer: prints the given number of lines of the stack trace</li>
830 </ul>
831
832 <p>Here are some examples:</p>
833
834 <table class="bodyTable">
835 <tr class="a">
836 <th>Conversion Pattern</th>
837 <th>Result</th>
838 </tr>
839 <tr class="b">
840 <td>%ex</td>
841 <td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
842 at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
843 at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
844 at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)</pre></td>
845 </tr>
846 <tr class="a">
847 <td>%ex{short}</td>
848 <td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
849 at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)</pre></td>
850 </tr>
851 <tr class="b">
852 <td>%ex{full}</td>
853 <td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
854 at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
855 at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
856 at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)</pre></td>
857 </tr>
858 <tr class="a">
859 <td>%ex{2}</td>
860 <td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
861 at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
862 at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)</pre></td>
863 </tr>
864 </table>
865
866 <p>This conversion word can also use evaluators to test
867 logging events against a given criterion before creating the
868 output. For example, using <b>%ex{full, EX_DISPLAY_EVAL}</b>
869 will display the full stack trace of the exception only if
870 the evaluator called <em>EX_DISPLAY_EVAL</em> returns a
871 <b>negative</b> answer. Evaluators are described further
872 down in this document.
873 </p>
874
875 <p>If you do not specify %throwable or another
876 throwable-related conversion word in the conversion pattern,
877 <code>PatternLayout</code> will automatically add it as the
878 last conversion word, on account of the importance of stack
879 trace information. The $nopex conversion word can be
880 substituted for %throwable, if you do not wish stack trace
881 information to be displayed. See also the %nopex conversion
882 word.
883 </p>
884
885 </td>
886 </tr>
887
888 <tr>
889 <td class="word" name="xThrowable">
890 <b>xEx</b>{<em>depth</em>} <br />
891 <b>xException</b>{<em>depth</em>} <br />
892 <b>xThrowable</b>{<em>depth</em>} <br />
893 <br />
894 <b>xEx</b>{depth, evaluator-1, ..., evaluator-n} <br />
895 <b>xException</b>{depth, evaluator-1, ..., evaluator-n} <br />
896 <b>xThrowable</b>{depth, evaluator-1, ..., evaluator-n}
897 </td>
898
899 <td>
900 <p>Same as the %throwable conversion word above with the
901 addition of class packaging information.</p>
902
903 <p>At the end of each stack frame of the exception, a string
904 consisting of the jar file containing the relevant class
905 followed by the "Implementation-Version" as found in that
906 jar's manifest will be added. This innovative technique was
907 <a
908 href="http://macstrac.blogspot.com/2008/09/better-stack-traces-in-java-with-log4j.html">originally suggested
909 by James Strachan</a>. If the information is uncertain, then
910 the class packaging data will be preceded by a tilde, i.e.
911 the '~' character.
912 </p>
913
914 <p>Here is an example:</p>
915
916 <p class="source small">java.lang.NullPointerException
917 at com.xyz.Wombat(Wombat.java:57) <b><span class="red">~</span>[wombat-1.3.jar:1.3]</b>
918 at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]
919 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_06]
920 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_06]
921 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.5.0_06]
922 at java.lang.reflect.Method.invoke(Method.java:585) ~[na:1.5.0_06]
923 at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59) [junit-4.4.jar:na]
924 at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98) [junit-4.4.jar:na]
925 ...etc </p>
926
927 <p>Logback goes to great lengths to ensure that the class
928 packaging information it displays is correct, even in
929 arbitrarily complex class loader hierarchies. However, when
930 it is unable to guarantee the absolute correctness of the
931 information, then it will prefix the data with a tilde, i.e.
932 the '~' character. Thus, it is theoretically possible for
933 the printed class packaging information to differ from the
934 real class packaging information. So, in the above example,
935 given that packaging data for the Wombat class is preceded
936 by a tilde, it is possible that the correct packaging data is
937 in reality [wombat.jar:1.7].
938 </p>
939
940 <p>Please note that given its potential cost, computation of
941 <a href="configuration.html#packagingData"><b>packaging data
942 is disabled by default</b></a>. When computation of
943 packaging data is enabled, <code>PatternLayout</code> will
944 automatically assume the %xThrowable suffix instead of
945 %throwable suffix at the end of the pattern string.</p>
946
947 <p><a
948 href="http://jira.qos.ch/browse/LBCLASSIC-212">Feedback from
949 users</a> indicates that Netbeans chokes on packaging
950 information.
951 </p>
952 </td>
953
954 </tr>
955
956 <tr>
957 <td class="word" name="nopex">
958 <b>nopex</b> <br />
959 <b>nopexception</b>
960 </td>
961
962 <td>
963 <p>Although it <em>pretends</em> to handle stack trace data,
964 this conversion word does not output any data, thus,
965 effectively ignoring exceptions.
966 </p>
967
968 <p>The %nopex conversion word allows the user to override
969 <code>PatternLayout</code>'s internal safety mechanism which
970 silently adds the %xThrowable conversion keyword in the absence of
971 another conversion word handling exceptions.
972 </p>
973 </td>
974 </tr>
975
976 <tr >
977 <td class="word" name="marker">
978 <b>marker</b>
979 </td>
980
981 <td>
982 <p>Outputs the marker associated with the logger
983 request.</p>
984
985 <p>In case the marker contains children markers, the
986 converter displays the parent as well as childrens' names
987 according to the format shown below.
988 </p>
989 <p>
990 <em>parentName [ child1, child2 ]</em>
991 </p>
992 </td>
993 </tr>
994
995
996 <tr>
997 <td class="word" name="property">
998 <b>property{key}</b>
999 </td>
1000
1001 <td><p>Outputs the value associated with a property named
1002 <em>key</em>. The the relevant docs on how to define ion
1003 entitled <a
1004 href="configuration.html#variableSubstitution">define
1005 variables</a> and <a href="configuration.html#scopes">variable
1006 scopes</a>.
1007
1008 <!-- XXXXXXXXXXXX -->
1009
1010 If <em>key</em> is not a property of
1011 the logger context, then <em>key</em> will be looked up in the
1012 System properties.</p>
1013
1014
1015 <p>There is no default value for <em>key</em>. If it is
1016 omitted, the returned value will be "Property_HAS_NO_KEY",
1017 expliciting the error condition.</p>
1018
1019 </td>
1020 </tr>
1021
1022 <tr>
1023 <td class="word" name="replace">
1024 <b>replace(<em>p</em>){r, t}</b>
1025 </td>
1026
1027 <td>
1028 <p>Replaces occurrences of 'r', a regex, with its
1029 replacement 't' in the string produces by the sub-pattern
1030 'p'. For example, "%replace(%msg){'\s', ''}" will remove all
1031 spaces contained in the event message.
1032 </p>
1033
1034 <p>The pattern 'p' can be arbitrarily complex and in
1035 particular can contain multiple conversion keywords. For
1036 instance, "%replace(%logger %msg){'\.', '/'}" will replace
1037 all dots in the logger or the message of the event with a
1038 forward slash.
1039 </p>
1040
1041 </td>
1042 </tr>
1043
1044
1045 <tr>
1046 <td class="word" name="rootException">
1047 <b>rEx</b>{<em>depth</em>} <br />
1048 <b>rootException</b>{<em>depth</em>} <br />
1049 <br />
1050 <b>rEx</b>{depth, evaluator-1, ..., evaluator-n} <br />
1051 <b>rootException</b>{depth, evaluator-1, ..., evaluator-n}
1052 </td>
1053
1054 <td>
1055 <p>Outputs the stack trace of the exception associated with
1056 the logging event, if any. The root cause will be output
1057 first instead of the standard "root cause last". Here is a
1058 sample output (edited for space):
1059 </p>
1060
1061 <pre class="small">java.lang.NullPointerException
1062 at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3]
1063 at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]
1064 Wrapped by: org.springframework.BeanCreationException: Error creating bean with name 'wombat':
1065 at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248) [spring-2.0.jar:2.0]
1066 at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170) [spring-2.0.jar:2.0]
1067 at org.apache.catalina.StandardContext.listenerStart(StandardContext.java:3934) [tomcat-6.0.26.jar:6.0.26]
1068 </pre>
1069
1070 <p>The %rootException converter admits the same optional
1071 parameters as the %xException converter described above,
1072 including depth and evaluators. It outputs also packaging
1073 information. In short, %rootException is very similar to
1074 %xException, only the order of exception output is reversed.
1075 </p>
1076
1077 <p>Tomasz Nurkiewicz, the author of %rootException converter,
1078 documents his contribution in a blog entry entitled <a
1079 href="http://nurkiewicz.blogspot.com/2011/09/logging-exceptions-root-cause-first.html">"Logging
1080 exceptions root cause first"</a>.</p>
1081 </td>
1082 </tr>
1083
1084 </table>
1085
1086
1087 <h4 class="doAnchor" name="percentIsSpecial">% character has special meaning</h4>
1088
1089 <p>Given that in the context of conversion patterns the percent
1090 sign carries special meaning, in order to include it as a literal,
1091 it needs to be escaped with a backslash, e.g. "%d %p <b>\%</b>
1092 %m%n".
1093 </p>
1094
1095 <h4 class="doAnchor" name="restrictionsOnLiterals">Restrictions on
1096 literals immediately following conversion words</h4>
1097
1098 <p>In most cases literals naturally contain spaces or other
1099 delimiting characters so that they are not confused with
1100 conversion words. For example, the pattern
1101 "%level&nbsp;[%thread]&nbsp;-&nbsp;%message%n" contains the string
1102 literals <code>"&nbsp;["</code> and
1103 <code>"]&nbsp;-&nbsp;"</code>. However, if a character which can
1104 be part of a java identifier immediately follows a conversion
1105 word, logback's pattern parser will be fooled into thinking that
1106 the literal is part of the conversion word. For example, the
1107 pattern "%date<b>%nHello</b>" will be interpreted as two
1108 conversion words %date and %nHello and since %nHello is not a
1109 known conversion word, logback will output %PARSER_ERROR[nHello]
1110 for %nHello. If you wish the string literal "Hello" to immediately
1111 separate %n and Hello, pass an empty argument list to %n. For
1112 example, "%date<b>%n{}</b>Hello" will be interpreted as %date
1113 followed by %n followed by the literal "Hello".
1114
1115 </p>
1116
1117 <h2 class="doAnchor" name="formatModifiers">Format modifiers</h2>
1118
1119 <p>By default the relevant information is output as-is. However,
1120 with the aid of format modifiers it is possible to change the
1121 minimum and maximum width and the justifications of each data
1122 field.
1123 </p>
1124
1125 <p>The optional format modifier is placed between the percent sign
1126 and the conversion character or word.
1127 </p>
1128
1129 <p>The first optional format modifier is the <em>left
1130 justification flag</em> which is just the minus (-)
1131 character. Then comes the optional <em>minimum field width</em>
1132 modifier. This is a decimal constant that represents the minimum
1133 number of characters to output. If the data item contains fewer
1134 characters, it is padded on either the left or the right until the
1135 minimum width is reached. The default is to pad on the left (right
1136 justify) but you can specify right padding with the left
1137 justification flag. The padding character is space. If the data
1138 item is larger than the minimum field width, the field is expanded
1139 to accommodate the data. The value is never truncated.
1140 </p>
1141
1142 <p>This behavior can be changed using the <em>maximum field
1143 width</em> modifier which is designated by a period followed by a
1144 decimal constant. If the data item is longer than the maximum
1145 field, then the extra characters are removed from the
1146 <em>beginning</em> of the data item. For example, if the maximum
1147 field width is eight and the data item is ten characters long,
1148 then the first two characters of the data item are dropped. This
1149 behavior deviates from the printf function in C where truncation
1150 is done from the end.
1151 </p>
1152
1153 <p>Truncation from the end is possible by appending a minus
1154 character right after the period. In that case, if the maximum
1155 field width is eight and the data item is ten characters long,
1156 then the last two characters of the data item are dropped.
1157 </p>
1158
1159 <p>Below are various format modifier examples for the logger
1160 conversion specifier.
1161 </p>
1162
1163 <table class="bodyTable" border="0" cellpadding="8">
1164 <tr>
1165 <th>Format modifier</th>
1166 <th>Left justify</th>
1167 <th>Minimum width</th>
1168 <th>Maximum width</th>
1169 <th>Comment</th>
1170 </tr>
1171 <tr class="a">
1172 <td align="center">%20logger</td>
1173 <td align="center">false</td>
1174 <td align="center">20</td>
1175 <td align="center">none</td>
1176 <td>
1177 Left pad with spaces if the logger name is less
1178 than 20 characters long.
1179 </td>
1180 </tr>
1181 <tr class="b">
1182 <td align="center">%-20logger</td>
1183 <td align="center">true</td>
1184 <td align="center">20</td>
1185 <td align="center">none</td>
1186 <td>
1187 Right pad with spaces if the logger name is less
1188 than 20 characters long.
1189 </td>
1190 </tr>
1191 <tr class="a">
1192 <td align="center">%.30logger</td>
1193 <td align="center">NA</td>
1194 <td align="center">none</td>
1195 <td align="center">30</td>
1196 <td>
1197 Truncate from the beginning if the logger name is
1198 longer than 30 characters.
1199 </td>
1200 </tr>
1201 <tr class="b">
1202 <td align="center">%20.30logger</td>
1203 <td align="center">false</td>
1204 <td align="center">20</td>
1205 <td align="center">30</td>
1206 <td>
1207 Left pad with spaces if the logger name is shorter
1208 than 20 characters. However, if logger name is
1209 longer than 30 characters, then truncate from the
1210 beginning.
1211 </td>
1212 </tr>
1213 <tr class="a">
1214 <td align="center">%-20.30logger</td>
1215 <td align="center">true</td>
1216 <td align="center">20</td>
1217 <td align="center">30</td>
1218 <td>
1219 Right pad with spaces if the logger name is shorter
1220 than 20 characters. However, if logger name is
1221 longer than 30 characters, then truncate from the
1222 <em>beginning</em>.
1223 </td>
1224 </tr>
1225 <tr class="b">
1226 <td align="center">%.-30logger</td>
1227 <td align="center">NA</td>
1228 <td align="center">none</td>
1229 <td align="center">30</td>
1230 <td>
1231 Truncate from the <em>end</em> if the logger name is
1232 longer than 30 characters.
1233 </td>
1234 </tr>
1235 </table>
1236
1237 <p>The table below list examples for format modifier
1238 truncation. Please note that the square brackets, i.e the pair of "[]"
1239 characters, are not part of the output. They are used to delimit
1240 the width of output.</p>
1241
1242
1243 <table class="bodyTable" border="0" cellpadding="8">
1244 <tr>
1245 <th>Format modifier</th>
1246 <th>Logger name</th>
1247 <th>Result</th>
1248 </tr>
1249 <tr class="b">
1250 <td align="center">[%20.20logger]</td>
1251 <td align="center">main.Name</td>
1252 <td align="center"><pre>[ main.Name]</pre></td>
1253 </tr>
1254 <tr class="a">
1255 <td align="center">[%-20.20logger]</td>
1256 <td align="center">main.Name</td>
1257 <td align="center"><pre>[main.Name ]</pre></td>
1258 </tr>
1259 <tr class="a">
1260 <td align="center">[%10.10logger]</td>
1261 <td align="center">main.foo.foo.bar.Name</td>
1262 <td align="center"><pre>[o.bar.Name]</pre></td>
1263 </tr>
1264 <tr class="b">
1265 <td align="center">[%10.-10logger]</td>
1266 <td align="center">main.foo.foo.bar.Name</td>
1267 <td align="center"><pre>[main.foo.f]</pre></td>
1268 </tr>
1269 </table>
1270
1271 <h3 class="doAnchor" name="oneLetterLevel">Output just one letter
1272 for the level</h3>
1273
1274 <p>Instead of printing TRACE, DEBUG, WARN, INFO or ERROR for the
1275 level, you may want to print just T, D, W, I and E. You could
1276 write a <a href="#customConversionSpecifier">custom converter</a>
1277 for this purpose, or simply make use of format modifiers (just
1278 discussed) to shorten the level value to a single character. The
1279 appropriate conversion specifier would be
1280 "<code>%.-1level</code>".
1281 </p>
1282
1283 <h2 class="doAnchor" name="cwOptions">Conversion word options</h2>
1284
1285 <p>A conversion specifier can be followed by options. The are
1286 always declared between braces. We have already seen some of the
1287 possibilities offered by options, for instance in conjunction with
1288 the MDC conversion specifier, as in: <em>%mdc{someKey}</em>.
1289 </p>
1290
1291 <p>A conversion specifier might have more than one option. For
1292 example, a conversion specifier that makes use of evaluators,
1293 which will be covered soon, may add evaluator names to the option
1294 list, as shown below:</p>
1295
1296 <pre class="prettyprint source">&lt;pattern>%-4relative [%thread] %-5level - %msg%n \
1297 <b>%caller{2, DISP_CALLER_EVAL, OTHER_EVAL_NAME, THIRD_EVAL_NAME}</b>&lt;/pattern></pre>
1298
1299 <p>If the option includes special characters such as a braces, spaces or
1300 commas, you can enclose it between single or double quotes. For
1301 example, consider the next pattern.</p>
1302
1303 <pre class="prettyprint source">&lt;pattern>%-5level - %replace(%msg)<b>{'\d{14,16}', 'XXXX'}</b>%n&lt;/pattern></pre>
1304
1305
1306 <p>We pass the options <code>\d{16}</code> and <code>XXXX</code>
1307 to the <code>replace</code> conversion word. It replaces any
1308 sequence of 14, 15 or 16 digits contained in the message with XXXX
1309 effectively obfuscating credit card numbers. Note that "\d" which
1310 is a shorthand for a single digit in regular expressions. The
1311 "{14,16\}" is interpreted as "{14, 16}", that is, repeat the
1312 previous item at least 14 but at most 16 times.
1313 </p>
1314
1315 <h2 class="doAnchor" name="Parentheses">Parentheses are
1316 special</h2>
1317
1318 <p>In logback, parentheses within the pattern string are treated
1319 as grouping tokens. Thus, it is possible to group a sub-pattern
1320 and apply formatting directives on that sub-pattern. As of version
1321 0.9.27, logback supports composite conversion words such as <a
1322 href="#replace">%replace</a> which can transform sub-patterns.
1323 </p>
1324
1325 <p>For example, the pattern</p>
1326
1327 <p class="source"><b>%-30(</b>%d{HH:mm:ss.SSS} [%thread]<b>)</b> %-5level %logger{32} - %msg%n</p>
1328
1329 <p>will group the output generated by the sub-pattern
1330 "%d{HH:mm:ss.SSS} [%thread]" so that it is right-padded if less
1331 than 30 characters.
1332 </p>
1333
1334 <p>If without the grouping the output was</p>
1335
1336 <p class="source">13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Classload hashcode is 13995234
1337 13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Initializing for ServletContext
1338 13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Trying platform Mbean server
1339 13:09:30 [pool-1-thread-1] INFO ch.qos.logback.demo.LoggingTask - Howdydy-diddly-ho - 0
1340 13:09:38 [btpool0-7] INFO c.q.l.demo.lottery.LotteryAction - Number: 50 was tried.
1341 13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Beginning to factor.
1342 13:09:40 [btpool0-7] DEBUG c.q.l.d.prime.NumberCruncherImpl - Trying 2 as a factor.
1343 13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Found factor 2
1344 </p>
1345
1346 <p>with the "%-30()" grouping it would be</p>
1347
1348 <p class="source">13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Classload hashcode is 13995234
1349 13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Initializing for ServletContext
1350 13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Trying platform Mbean server
1351 13:09:30 [pool-1-thread-1] INFO ch.qos.logback.demo.LoggingTask - Howdydy-diddly-ho - 0
1352 13:09:38 [btpool0-7] INFO c.q.l.demo.lottery.LotteryAction - Number: 50 was tried.
1353 13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Beginning to factor.
1354 13:09:40 [btpool0-7] DEBUG c.q.l.d.prime.NumberCruncherImpl - Trying 2 as a factor.
1355 13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Found factor 2
1356 </p>
1357
1358
1359 <p>The latter form is more comfortable to read.</p>
1360
1361 <p>If you need to treat the parenthesis character as a literal, it
1362 needs to be escaped by preceding each parenthesis with a
1363 backslash. As in, <b>\(</b>%d{HH:mm:ss.SSS}
1364 [%thread]<b>\)</b>.
1365 </p>
1366
1367 <h2 class="doAnchor" name="coloring">Coloring</h2>
1368
1369 <p>Grouping by <a href="#Parentheses">parentheses</a> as explained
1370 above allows coloring of sub-patterns. As of version 1.0.5,
1371 <code>PatternLayout</code> recognizes "%black", "%red",
1372 "%green","%yellow","%blue", "%magenta","%cyan", "%white", "%gray",
1373 "%boldRed","%boldGreen", "%boldYellow", "%boldBlue",
1374 "%boldMagenta""%boldCyan", "%boldWhite" and "%highlight" as
1375 conversion words. These conversion words are intended to contain a
1376 sub-pattern. Any sub-pattern enclosed by a coloring word will be
1377 output in the specified color.
1378 </p>
1379
1380 <p>Below is a configuration file illustrating coloring. Note the
1381 %cyan conversion specifier enclosing "%logger{15}". This will
1382 output the logger name abbreviated to 15 characters in cyan. The
1383 %highlight conversion specifier prints its sub-pattern in bold-red
1384 for events of level ERROR, in red for WARN, in BLUE for INFO, and
1385 in the default color for other levels.</p>
1386
1387 <em>
1388 Example: Highlighting levels
1389 (logback-examples/src/main/resources/chapters/layouts/highlighted.xml)
1390 </em>
1391
1392 <span class="asGroovy" onclick="return asGroovy('highlighted');">View as .groovy</span>
1393
1394
1395 <pre id="highlighted" class="prettyprint">&lt;configuration debug="true">
1396 &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
1397 &lt;!-- On Windows machines setting withJansi to true enables ANSI
1398 color code interpretation by the Jansi library. This requires
1399 org.fusesource.jansi:jansi:1.8 on the class path. Note that
1400 Unix-based operating systems such as Linux and Mac OS X
1401 support ANSI color codes by default. --&gt;
1402 <b>&lt;withJansi>true&lt;/withJansi></b>
1403 &lt;encoder>
1404 &lt;pattern>[%thread] <b>%highlight(%-5level)</b> <b>%cyan(%logger{15})</b> - %msg %n&lt;/pattern>
1405 &lt;/encoder>
1406 &lt;/appender>
1407 &lt;root level="DEBUG">
1408 &lt;appender-ref ref="STDOUT" />
1409 &lt;/root>
1410 &lt;/configuration></pre>
1411
1412 <p>Here is the corresponding output:</p>
1413
1414 <pre class="source">[main] <span style="color:#611">WARN</span> <span style="color:#2bd">c.l.TrivialMain</span> - a warning message 0
1415 [main] DEBUG <span style="color:#2bd">c.l.TrivialMain</span> - hello world number1
1416 [main] DEBUG <span style="color:#2bd">c.l.TrivialMain</span> - hello world number2
1417 [main] <span style="color:#00F">INFO</span> <span style="color:#2bd">c.l.TrivialMain</span> - hello world number3
1418 [main] DEBUG <span style="color:#2bd">c.l.TrivialMain</span> - hello world number4
1419 [main] <span style="color:#611">WARN</span> <span style="color:#2bd">c.l.TrivialMain</span> - a warning message 5
1420 [main] <span style="color:#F00">ERROR</span> <span style="color:#2bd">c.l.TrivialMain</span> - Finish off with fireworks</pre>
1421
1422 <p>It takes very few lines of code to create a coloring conversion
1423 word. The section entitled <a
1424 href="#customConversionSpecifier">creating a custom conversion
1425 specifier</a> discusses the steps necessary for registering a
1426 conversion word in your configuration file.</p>
1427
1428 <h2 class="doAnchor" name="Evaluators">Evaluators</h2>
1429
1430 <p>As mentioned above, option lists come in handy when a
1431 conversion specifier is required to behave dynamically based on
1432 one or more
1433 <a href="../xref/ch/qos/logback/core/boolex/EventEvaluator.html">
1434 <code>EventEvaluator</code></a> objects.
1435 <code>EventEvaluator</code> objects have the responsibility to
1436 determine whether a given logging event matches the criteria of the
1437 evaluator.
1438 </p>
1439
1440 <p>Let us review an example involving a
1441 <code>EventEvaluator</code>. The next configuration file outputs
1442 the logging events to the console, displaying date, thread, level,
1443 message and caller data. Given that extracting the caller data of
1444 a logging event is on the expensive side, we will do so only when
1445 the logging request originates from a specific logger, and when
1446 the message contains a certain string. Thus, we make sure that only
1447 specific logging requests will have their caller information
1448 generated and displayed. In other cases, where the caller data is
1449 superfluous, we will not penalize application performance.
1450 </p>
1451
1452 <p>Evaluators and in particular <em>evaluation expressions</em>
1453 are presented in a <a
1454 href="filters.html#evalutatorFilter">dedicated section of the
1455 chapter on filters</a> which you MUST read if you want to use
1456 evaluators in any meaningful way. Also note that the examples below
1457 are implicitly based on <code>JaninoEventEvaluator</code> which
1458 requires the <a
1459 href="http://docs.codehaus.org/display/JANINO/Home">Janino
1460 library</a>. Please see the <a
1461 href="../setup.html#janino">corresponding section</a> of the setup
1462 document.</p>
1463
1464 <em>
1465 Example: Sample usage of EventEvaluators
1466 (logback-examples/src/main/resources/chapters/layouts/callerEvaluatorConfig.xml)
1467 </em>
1468
1469 <span class="asGroovy" onclick="return asGroovy('callerEvaluatorConfig');">View as .groovy</span>
1470
1471
1472 <pre id="callerEvaluatorConfig" class="prettyprint source">&lt;configuration>
1473 <b>&lt;evaluator name="DISP_CALLER_EVAL">
1474 &lt;expression>logger.contains("chapters.layouts") &amp;amp;&amp;amp; \
1475 message.contains("who calls thee")&lt;/expression>
1476 &lt;/evaluator></b>
1477
1478 &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
1479 &lt;encoder>
1480 &lt;pattern>
1481 %-4relative [%thread] %-5level - %msg%n<b>%caller{2, DISP_CALLER_EVAL}</b>
1482 &lt;/pattern>
1483 &lt;/encoder>
1484 &lt;/appender>
1485
1486 &lt;root level="DEBUG">
1487 &lt;appender-ref ref="STDOUT" />
1488 &lt;/root>
1489 &lt;/configuration></pre>
1490
1491 <p>The above evaluation expression matches events which emanate
1492 from a logger with a name containing the string "chapters.layouts"
1493 and the message contains the string "who calls thee". Due to XML
1494 encoding rules, the &amp; character cannot be written as is, and
1495 needs to be escaped as &amp;amp;.</p>
1496
1497 <p>The following class makes use of some of the characteristics
1498 mentioned in above configuration file.</p>
1499
1500 <p><em>
1501 Example: Sample usage of EventEvaluators
1502 <a href="../xref/chapters/layouts/CallerEvaluatorExample.html">
1503 (logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java)</a>
1504 </em>
1505 </p>
1506 <pre class="prettyprint source">package <b>chapters.layouts</b>;
1507
1508 import org.slf4j.Logger;
1509 import org.slf4j.LoggerFactory;
1510
1511 import ch.qos.logback.classic.LoggerContext;
1512 import ch.qos.logback.classic.joran.JoranConfigurator;
1513 import ch.qos.logback.core.joran.spi.JoranException;
1514 import ch.qos.logback.core.util.StatusPrinter;
1515
1516 public class CallerEvaluatorExample {
1517
1518 public static void main(String[] args) {
1519 Logger logger = LoggerFactory.getLogger(CallerEvaluatorExample.class);
1520 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
1521
1522 try {
1523 JoranConfigurator configurator = new JoranConfigurator();
1524 configurator.setContext(lc);
1525 configurator.doConfigure(args[0]);
1526 } catch (JoranException je) {
1527 // StatusPrinter will handle this
1528 }
1529 StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
1530
1531 for (int i = 0; i &lt; 5; i++) {
1532 if (i == 3) {
1533 logger.debug(<b>"who calls thee</b>?");
1534 } else {
1535 logger.debug("I know me " + i);
1536 }
1537 }
1538 }
1539 }</pre>
1540
1541 <p>The above application does nothing particularly fancy. Five
1542 logging requests are issued, the third one emitting the message
1543 "who calls thee?"
1544 </p>
1545
1546 <p>The command</p>
1547
1548 <p class="source">java chapters.layouts.CallerEvaluatorExample src/main/java/chapters/layouts/callerEvaluatorConfig.xml</p>
1549
1550 <p>will yield</p>
1551
1552 <div class="source"><pre>0 [main] DEBUG - I know me 0
1553 0 [main] DEBUG - I know me 1
1554 0 [main] DEBUG - I know me 2
1555 0 [main] DEBUG - who calls thee?
1556 Caller+0 at chapters.layouts.CallerEvaluatorExample.main(CallerEvaluatorExample.java:28)
1557 0 [main] DEBUG - I know me 4</pre></div>
1558
1559
1560 <p>When a logging request is issued, the corresponding logging
1561 event is evaluated. Only the third logging event matches the
1562 evaluation criteria, causing its caller data to be displayed. For
1563 other logging events, the evaluation criteria do not match and no
1564 caller data is printed.
1565 </p>
1566
1567
1568 <p>One can change the expression to correspond a real world
1569 scenario. For instance, one could combine the logger name and
1570 request level. Thus, logging requests of level <em>WARN</em> and
1571 up, originating from a sensitive part of an application, e.g. a
1572 financial transaction module, would have their caller data
1573 displayed.
1574 </p>
1575
1576 <p><b>Important:</b> With the <em>caller</em> conversion word,
1577 caller data is output when <em>the expression evaluates to
1578 <b>true</b>.</em></p>
1579
1580 <p>Let us consider at a different situation. When exceptions are
1581 included in a logging request, their stack trace is also
1582 output. However, one might want to suppress the stack trace for
1583 some specific exceptions.
1584 </p>
1585
1586 <p>The Java code shown below creates three log requests, each with
1587 an exception. The second exception is different from the others:
1588 it contains the string "do not display this" and it is of type
1589 <code>chapters.layouts.TestException</code>. As its message
1590 commands, let us now prevent the second exception from being
1591 printed.</p>
1592
1593 <p><em>
1594 Example: Sample usage of EventEvaluators
1595 <a href="../xref/chapters/layouts/ExceptionEvaluatorExample.html">
1596 (logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java)</a>
1597 </em>
1598 </p>
1599 <pre class="prettyprint source">package chapters.layouts;
1600
1601 import org.slf4j.Logger;
1602 import org.slf4j.LoggerFactory;
1603
1604 import ch.qos.logback.classic.LoggerContext;
1605 import ch.qos.logback.classic.joran.JoranConfigurator;
1606 import ch.qos.logback.core.joran.spi.JoranException;
1607 import ch.qos.logback.core.util.StatusPrinter;
1608
1609 public class ExceptionEvaluatorExample {
1610
1611 public static void main(String[] args) {
1612 Logger logger = LoggerFactory.getLogger(ExceptionEvaluatorExample.class);
1613 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
1614
1615 try {
1616 JoranConfigurator configurator = new JoranConfigurator();
1617 configurator.setContext(lc);
1618 lc.reset();
1619 configurator.doConfigure(args[0]);
1620 } catch (JoranException je) {
1621 // StatusPrinter will handle this
1622 }
1623 StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
1624
1625 for (int i = 0; i &lt; 3; i++) {
1626 if (i == 1) {
1627 logger.debug("logging statement " + i, new TestException(
1628 "do not display this"));
1629 } else {
1630 logger.debug("logging statement " + i, new Exception("display"));
1631 }
1632 }
1633 }
1634 }</pre>
1635
1636 <p>In the next configuration file, the evaluation expression
1637 matches events containing a throwable of type
1638 <code>chapters.layouts.TextException</code>, precisely the type of
1639 exceptions we wish to suppress.
1640 </p>
1641
1642 <em>
1643 Example: Sample usage of EventEvaluators
1644 (logback-examples/src/main/resources/chapters/layouts/exceptionEvaluatorConfig.xml)
1645 </em>
1646 <pre class="prettyprint source">&lt;configuration>
1647
1648 <b>&lt;evaluator name="DISPLAY_EX_EVAL">
1649 &lt;expression>throwable != null &amp;amp;&amp;amp; throwable instanceof \
1650 chapters.layouts.TestException&lt;/expression>
1651 &lt;/evaluator></b>
1652
1653 &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
1654 &lt;encoder>
1655 &lt;pattern>%msg%n<b>%ex{full, DISPLAY_EX_EVAL}</b>&lt;/pattern>
1656 &lt;/encoder>
1657 &lt;/appender>
1658
1659 &lt;root level="debug">
1660 &lt;appender-ref ref="STDOUT" />
1661 &lt;/root>
1662 &lt;/configuration></pre>
1663
1664 <p>With this configuration, each time an instance of the
1665 <em>chapters.layouts.TestException</em> is included within a logging
1666 request, the stack trace will be suppressed.
1667 </p>
1668
1669 <p>Launching the command</p>
1670
1671 <p class="source">java chapters.layouts.ExceptionEvaluatorExample src/main/java/chapters/layouts/exceptionEvaluatorConfig.xml</p>
1672
1673 <p>will yield</p>
1674
1675 <p class="source">logging statement 0
1676 java.lang.Exception: display
1677 at chapters.layouts.ExceptionEvaluatorExample.main(ExceptionEvaluatorExample.java:43) [logback-examples-0.9.19.jar:na]
1678 logging statement 1
1679 logging statement 2
1680 java.lang.Exception: display
1681 at chapters.layouts.ExceptionEvaluatorExample.main(ExceptionEvaluatorExample.java:43) [logback-examples-0.9.19.jar:na]</p>
1682
1683
1684 <p>Notice how the second log statement has no stack trace. We
1685 effectively suppressed the stack trace for the
1686 <code>TextException</code>. The text between square brackets at
1687 the end of each stack trace line is <a
1688 href="#xThrowable">packaging information</a> discussed
1689 earlier.</p>
1690
1691 <p><span class="label notice">Note</span> With the <b><em>%ex</em></b> conversion
1692 specifier, the stack trace is displayed when <em>the expression
1693 evaluates to <b>false</b>.</em></p>
1694
1695
1696
1697 <h2 class="doAnchor" name="customConversionSpecifier">Creating a
1698 custom conversion specifier</h2>
1699
1700 <p>Up to this point we have presented the built-in conversion
1701 words in <code>PatternLayout</code>. But it is also possible to
1702 add conversion words of your own making.</p>
1703
1704 <p>Building a custom conversion specifier consists of two steps.
1705 </p>
1706
1707 <h4>Step 1</h4>
1708
1709 <p>First, you must extend the <code>ClassicConverter</code>
1710 class. <a
1711 href="../xref/ch/qos/logback/classic/pattern/ClassicConverter.html">
1712 <code>ClassicConverter</code></a> objects are responsible for
1713 extracting information out of <code>ILoggingEvent</code> instances
1714 and producing a String. For example,
1715 <a href="../xref/ch/qos/logback/classic/pattern/LoggerConverter.html">
1716 <code>LoggerConverter</code></a>, the converter underlying the
1717 %logger conversion word, extracts the name of the logger from
1718 <code>ILoggingEvent</code> and returns it as a String. It might
1719 abbreviate the logger name in the process.</p>
1720
1721 <p>Here is a customer converter which returns the time elapsed
1722 since its creaton in nanoseconds:</p>
1723
1724 <em> Example: Sample Converter Example
1725 <a href="../xref/chapters/layouts/MySampleConverter.html">
1726 (src/main/java/chapters/layouts/MySampleConverter.java)</a></em>
1727 <pre class="prettyprint source">public class MySampleConverter extends ClassicConverter {
1728
1729 long start = System.nanoTime();
1730
1731 <b>@Override</b>
1732 <b>public String convert(ILoggingEvent event) {</b>
1733 <b>long nowInNanos = System.nanoTime();</b>
1734 <b>return Long.toString(nowInNanos-start);</b>
1735 <b>}</b>
1736 }</pre>
1737
1738 <p>This implementation is pretty straightforward. The
1739 <code>MySampleConverter</code> class extends
1740 <code>ClassicConverter</code>, and implements the
1741 <code>convert</code> method which returns the number of
1742 nano-seconds elapsed since its creation.
1743 </p>
1744
1745 <h4>Step 2</h4>
1746
1747 <p>In the second step, we must let logback know about the new
1748 <code>Converter</code>. For this purpose, we need to declare the
1749 new conversion word in the configuration file, as shown below:</p>
1750
1751 <em> Example: Sample Converter Example (src/main/java/chapters/layouts/mySampleConverterConfig.xml)</em>
1752 <span class="asGroovy" onclick="return asGroovy('mySampleConverterConfig');">View as .groovy</span>
1753 <pre id="mySampleConverterConfig" class="prettyprint source">&lt;configuration>
1754
1755 <b>&lt;conversionRule conversionWord="nanos"
1756 converterClass="chapters.layouts.MySampleConverter" /></b>
1757
1758 &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
1759 &lt;encoder>
1760 &lt;pattern><b>%-6nanos</b> [%thread] - %msg%n&lt;/pattern>
1761 &lt;/encoder>
1762 &lt;/appender>
1763
1764 &lt;root level="DEBUG">
1765 &lt;appender-ref ref="STDOUT" />
1766 &lt;/root>
1767 &lt;/configuration></pre>
1768
1769 <p>Once the new conversion word has been declared in the
1770 configuration file, we can refer to it within
1771 <code>PatternLayout</code> pattern, as with any other
1772 conversion word.</p>
1773
1774 <p>The command:</p>
1775
1776 <div class="source">java chapters.layouts.SampleLogging src/main/java/chapters/layouts/mySampleConverterConfig.xml </div>
1777
1778 <p>should yield output akin to:</p>
1779
1780 <pre class="source">4868695 [main] DEBUG - Everything's going well
1781 5758748 [main] ERROR - maybe not quite...</pre>
1782
1783
1784 <p>The reader might want to take a look at other
1785 <code>Converter</code> implementations such as
1786 <a href="../xref/ch/qos/logback/classic/pattern/MDCConverter.html">
1787 <code>MDCConverter</code></a> to learn about more complex
1788 behaviours, such as option handling. For creating your own
1789 coloring schemes have a look at <a
1790 href="../xref/ch/qos/logback/classic/pattern/color/HighlightingCompositeConverter.html"><code>HighlightingCompositeConverter</code></a>.
1791 </p>
1792
1793
1794
1795 <h2 class="doAnchor" name="ClassicHTMLLayout">HTMLLayout</h2>
1796
1797 <p><a
1798 href="../xref/ch/qos/logback/classic/html/HTMLLayout.html"><code>HTMLLayout</code></a>
1799 (as included in logback-classic) generates logs in HTML
1800 format. <code>HTMLLayout</code> outputs logging events in an HTML
1801 table where each row of the table corresponds to a logging
1802 event.</p>
1803
1804 <p>Here is a sample output produced by <code>HTMLLayout</code>
1805 using its default CSS stylesheet:</p>
1806 <img src="images/chapters/layouts/htmlLayout0.gif" alt="HTML Layout Sample Image"/>
1807
1808 <p>The content of table columns are specified with the help of a
1809 conversion pattern. See <a
1810 href="#ClassicPatternLayout"><code>PatternLayout</code></a> for
1811 documentation on conversion patterns. As such, you have full
1812 control over the contents and format of the table. You can select
1813 and display any combination of converters
1814 <code>PatternLayout</code> knows about.
1815 </p>
1816
1817 <p>One notable exception about the use of
1818 <code>PatternLayout</code> with <code>HTMLLayout</code> is that
1819 conversion specifiers should not be separated by space characters
1820 or more generally by literal text. Each specifier found in the
1821 pattern will result in a separate column. Likewise a separate
1822 column will be generated for each block of literal text found in
1823 the pattern, potentially wasting valuable real-estate on your
1824 screen.</p>
1825
1826 <p>Here is simple but functional configuration file illustrating
1827 the use of <code>HTMLLayout</code>.
1828 </p>
1829
1830 <em> Example: HTMLLayout Example (src/main/java/chapters/layouts/htmlLayoutConfig1.xml)</em>
1831 <span class="asGroovy" onclick="return asGroovy('htmlLayoutConfig1');">View as .groovy</span>
1832 <pre id="htmlLayoutConfig1" class="prettyprint source">&lt;configuration debug="true"&gt;
1833 &lt;appender name="FILE" class="ch.qos.logback.core.FileAppender"&gt;
1834 &lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
1835 &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
1836 <b>&lt;pattern&gt;%relative%thread%mdc%level%logger%msg&lt;/pattern&gt;</b>
1837 &lt;/layout&gt;
1838 &lt;/encoder>
1839 &lt;file>test.html&lt;/file&gt;
1840 &lt;/appender&gt;
1841
1842 &lt;root level="DEBUG">
1843 &lt;appender-ref ref="FILE" />
1844 &lt;/root>
1845 &lt;/configuration>
1846 </pre>
1847
1848 <p>The <a
1849 href="../xref/chapters/layouts/TrivialMain.html">TrivialMain</a>
1850 application logs a few messages finishing with an exception. The
1851 command:</p>
1852
1853 <p class="source">java chapters.layouts.TrivialMain src/main/java/chapters/layouts/htmlLayoutConfig1.xml</p>
1854
1855 <p>will create the file <em>test.html</em> in the current
1856 folder. The contents of <em>test.html</em> should be similar to:
1857 </p>
1858 <img src="images/chapters/layouts/htmlLayout1.png" alt="HTML Layout Sample Image"/>
1859
1860 <h3>Stack traces</h3>
1861
1862 <p> If you use the <em>%em</em> conversion word to display stack
1863 traces, a table column will be created to display stack traces. In
1864 most cases the column will be empty, wasting screen
1865 real-estate. Moreover, printing a stack trace on a separate column
1866 does not yield very readable results. Fortunately, the
1867 <em>%ex</em> conversion word is not the only way to display stack
1868 traces.
1869 </p>
1870
1871 <p>A better solution is available through implementations of
1872 <code>IThrowableRenderer</code> interface. Such an implementation
1873 can be assigned to <code>HTMLLayout</code> to manage the display
1874 data related to exceptions. By default, a
1875 <a href="../xref/ch/qos/logback/classic/html/DefaultThrowableRenderer.html">
1876 <code>DefaultThrowableRenderer</code></a> is assigned to each
1877 <code>HTMLLayout</code> instance. It writes exceptions on a
1878 <em>new table row</em>, along with its stack trace, in an easily
1879 readable manner, as shown on the figure above.
1880 </p>
1881
1882 <p>If for some reason, you still wish to use the <em>%ex</em>
1883 pattern, then you can specify <a
1884 href="../xref/ch/qos/logback/core/html/NOPThrowableRenderer.html">
1885 <code>NOPThrowableRenderer</code></a> in the configuration file in
1886 order to disable displaying a separate row for the stack trace. We
1887 don't have the faintest idea why you would want to do that, but if
1888 you wished, you could.
1889 </p>
1890
1891 <h3>CSS</h3>
1892
1893 <p>The presentation of the HTML created by <code>HTMLLayout</code>
1894 is controlled through a Cascading Style Sheet (CSS). In the
1895 absence of specific instructions, <code>HTMLLayout</code> will
1896 default to its internal CSS. However, you can instruct
1897 <code>HTMLLayout</code> to use an external CSS file. For this
1898 purpose a <code>cssBuilder</code> element can be nested within a
1899 <code>&lt;layout&gt;</code> element, as shown below.
1900 </p>
1901
1902 <pre class="prettyprint source">&lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
1903 &lt;pattern>%relative...%msg&lt;/pattern>
1904 &lt;cssBuilder class="ch.qos.logback.classic.html.UrlCssBuilder">
1905 &lt;!-- url where the css file is located --&gt;
1906 &lt;url>http://...&lt;/url>
1907 &lt;/cssBuilder>
1908 &lt;/layout></pre>
1909
1910
1911 <p>The <code>HTMLLayout</code> is often used in conjunction with
1912 <code>SMTPAppender</code> so that outgoing email is pleasantly
1913 formatted in HTML.
1914 </p>
1915
1916
1917 <h2 class="doAnchor" name="log4jXMLLayout">Log4j XMLLayout</h2>
1918
1919 <p><a
1920 href="../xref/ch/qos/logback/classic/log4j/XMLLayout.html">XMLLayout</a>
1921 (part of logback-classic) generates output in a log4j.dtd
1922 compliant format to interoperate with tools such as <a
1923 href="http://logging.apache.org/chainsaw/index.html">Chainsaw</a>
1924 and <a href="http://vigilog.sourceforge.net/">Vigilog</a> capable
1925 of processing files generated by <a
1926 href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/XMLLayout.html">log4j's
1927 XMLLayout</a>.
1928 </p>
1929
1930
1931 <p>As the original XMLLayout in log4j version 1.2.15, XMLLayout in
1932 logback-classic takes two boolean properties, <span
1933 class="option">locationInfo</span> and <span
1934 class="option">properties</span>. Setting <span
1935 class="option">locationInfo</span> to true enables the inclusion
1936 of location info (caller data) in the each event. Setting <span
1937 class="option">properties</span> to true enables the inclusion of
1938 MDC information. Both options are set to false by default.
1939 </p>
1940
1941 <p>Here is a sample configuration</p>
1942
1943 <em> Example: Log4jXMLLayout Example (src/main/java/chapters/layouts/log4jXMLLayout.xml)</em>
1944 <span class="asGroovy" onclick="return asGroovy('log4jXMLLayout');">View as .groovy</span>
1945 <pre id="log4jXMLLayout" class="prettyprint source">&lt;configuration>
1946 &lt;appender name="FILE" class="ch.qos.logback.core.FileAppender">
1947 &lt;file>test.xml&lt;/file>
1948 &lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
1949 &lt;layout class="ch.qos.logback.classic.log4j.XMLLayout">
1950 &lt;locationInfo>true&lt;/locationInfo>
1951 &lt;/layout>
1952 &lt;/encoder>
1953 &lt;/appender>
1954
1955 &lt;root level="DEBUG">
1956 &lt;appender-ref ref="FILE" />
1957 &lt;/root>
1958 &lt;/configuration> </pre>
1959
1960 <h1 class="doAnchor" name="logback-access">Logback access</h1>
1961
1962 <p>Most logback-access layouts are mere adaptations of
1963 logback-classic layouts. Logback-classic and logback-access
1964 modules address different needs, but in general offer comparable
1965 functionality.</p>
1966
1967 <h2>Writing your own Layout</h2>
1968
1969 <p>Writing a custom <code>Layout</code> for logback access is
1970 nearly identical to its sibling <code>Layout</code> in
1971 logback-classic.</p>
1972
1973
1974 <h3 class="doAnchor" name="AccessPatternLayout">PatternLayout</h3>
1975
1976 <p><a href="../xref/ch/qos/logback/access/PatternLayout.html">
1977 <code>PatternLayout</code></a> in logback-access can be configured
1978 in much the same way as its classic counterpart. However it
1979 features additional conversion specifiers suited for logging
1980 particular bits of information available only in HTTP servlet
1981 requests and HTTP servlet responses.
1982 </p>
1983
1984 <p>Below is a list of conversion specifiers for
1985 <code>PatternLayout</code> in logback-access.</p>
1986
1987 <table class="bodyTable striped" border="0" cellpadding="8">
1988 <tr>
1989 <th align="center">Conversion Word</th>
1990 <th align="center">Effect</th>
1991 </tr>
1992 <tr>
1993 <td class="word" name="remoteIP">
1994 <b>a / remoteIP</b>
1995 </td>
1996 <td>
1997 <p>Remote IP address.</p>
1998 </td>
1999 </tr>
2000 <tr>
2001 <td class="word" name="localIP"><b>A / localIP</b></td>
2002 <td>
2003 <p>Local IP address.</p>
2004 </td>
2005 </tr>
2006 <tr>
2007 <td class="word" name="bytesSent"><b>b / B / bytesSent</b></td>
2008 <td>
2009 <p>
2010 Response's content length.
2011 </p>
2012 </td>
2013 </tr>
2014 <tr>
2015 <td class="word" name="clientHost"><b>h / clientHost</b></td>
2016 <td>
2017 <p>
2018 Remote host.
2019 </p>
2020 </td>
2021 </tr>
2022 <tr>
2023 <td class="word" name="protocol"><b>H / protocol</b></td>
2024 <td>
2025 <p>Request protocol.</p>
2026 </td>
2027 </tr>
2028 <tr>
2029 <td class="word" name="remoteLogName"><b>l</b></td>
2030 <td>
2031 <p>
2032 Remote log name. In logback-access, this converter always
2033 returns the value "-".
2034 </p>
2035 </td>
2036 </tr>
2037
2038 <tr>
2039 <td class="word" name="reqParameter"><b>reqParameter{paramName}</b></td>
2040 <td>
2041 <p>Parameter of the response.</p>
2042 <p>This conversion word takes the first option in braces and looks
2043 for the corresponding parameter in the request.</p>
2044 <p><b>%reqParameter{input_data}</b>
2045 displays the corresponding parameter.</p>
2046 </td>
2047 </tr>
2048 <tr>
2049 <td class="word" name="header"><b>i{header} / header{header}</b></td>
2050 <td>
2051 <p>Request header.</p>
2052 <p>This conversion word takes the first option in braces and looks
2053 for the corresponding header in the request.</p>
2054 <p><b>%header{Referer}</b> displays the referer of the request.</p>
2055 <p>
2056 If no option is specified, it displays every available header.
2057 </p>
2058 </td>
2059 </tr>
2060 <tr >
2061 <td class="word" name="requestMethod"><b>m / requestMethod</b></td>
2062 <td>
2063 <p>Request method.</p>
2064 </td>
2065 </tr>
2066 <tr>
2067 <td class="word" name="requestURL"><b>r / requestURL</b></td>
2068 <td>
2069 <p>
2070 URL requested.
2071 </p>
2072 </td>
2073 </tr>
2074 <tr>
2075 <td class="word" name="statusCode"><b>s / statusCode</b></td>
2076 <td>
2077 <p>
2078 Status code of the request.
2079 </p>
2080 </td>
2081 </tr>
2082 <tr>
2083 <td class="word" name="elapsedTime"><b>D / elapsedTime</b></td>
2084 <td>
2085 <p>
2086 The time taken to serve the request, in milliseconds.
2087 </p>
2088 </td>
2089 </tr>
2090 <tr>
2091 <td class="word" name="elapsedSeconds"><b>T / elapsedSeconds</b></td>
2092 <td>
2093 <p>
2094 The time taken to serve the request, in seconds.
2095 </p>
2096 </td>
2097 </tr>
2098 <tr>
2099 <td class="word" name="dateAccess"><b>t / date</b></td>
2100 <td>
2101 <p>Outputs the date of the logging event. The date
2102 conversion specifier may be followed by a set of braces
2103 containing a date and time pattern strings used by
2104 <code>java.text.SimpleDateFormat</code>. <em>ISO8601</em>
2105 is also a valid value.
2106 </p>
2107 <p>For example, <b>%t{HH:mm:ss,SSS}</b> or
2108 <b>%t{dd&nbsp;MMM&nbsp;yyyy&nbsp;;HH:mm:ss,SSS}</b>.
2109 If no date format specifier is given then the
2110 Common Log Format date format is assumed, that is: <b>%t{dd/MMM/yyyy:HH:mm:ss&nbsp;Z}</b>
2111 </p>
2112 </td>
2113 </tr>
2114 <tr>
2115 <td class="word" name="httpUser"><b>u / user</b></td>
2116 <td>
2117 <p>
2118 Remote user.
2119 </p>
2120 </td>
2121 </tr>
2122 <tr>
2123 <td class="word" name="queryString"><b>q / queryString</b></td>
2124 <td>
2125 <p>
2126 Request query string, prepended with a '?'.
2127 </p>
2128 </td>
2129 </tr>
2130 <tr>
2131 <td class="word" name="requestURI"><b>U / requestURI</b></td>
2132 <td>
2133 <p>
2134 Requested URI.
2135 </p>
2136 </td>
2137 </tr>
2138 <tr>
2139 <td class="word" name="sessionID"><b>S / sessionID</b></td>
2140 <td>
2141 <p>Session ID.</p>
2142 </td>
2143 </tr>
2144 <tr >
2145 <td class="word" name="server"><b>v / server</b></td>
2146 <td>
2147 <p>Server name.</p>
2148 </td>
2149 </tr>
2150 <tr>
2151 <td class="word" name="threadName"><b>I / threadName</b></td>
2152 <td>
2153 <p>Name of the thread which processed the request.</p>
2154 </td>
2155 </tr>
2156 <tr class="b">
2157 <td class="word" name="localPort"><b>localPort</b></td>
2158 <td>
2159 <p>Local port.</p>
2160 </td>
2161 </tr>
2162 <tr class="a">
2163 <td class="word" name="reqAttribute"><b>reqAttribute{attributeName}</b></td>
2164 <td>
2165 <p>Attribute of the request.</p>
2166 <p>This conversion word takes the first option in braces and looks
2167 for the corresponding attribute in the request.</p>
2168 <p><b>%reqAttribute{SOME_ATTRIBUTE}</b>
2169 displays the corresponding attribute.</p>
2170 </td>
2171 </tr>
2172 <tr class="b">
2173 <td class="word" name="reqCookie"><b>reqCookie{cookie}</b></td>
2174 <td>
2175 <p>Request cookie.</p>
2176 <p>This conversion word takes the first option in braces and looks
2177 for the corresponding cookie in the request.</p>
2178 <p><b>%cookie{COOKIE_NAME}</b> displays corresponding cookie.</p>
2179 </td>
2180 </tr>
2181 <tr class="a">
2182 <td class="word" name="responseHeader"><b>responseHeader{header}</b></td>
2183 <td>
2184 <p>
2185 Header of the response.
2186 </p>
2187 <p>This conversion word takes the first option in braces and looks
2188 for the corresponding header in the response.</p>
2189 <p><b>%header{Referer}</b> displays the referer of the response.</p>
2190 </td>
2191 </tr>
2192 <tr class="b">
2193 <td class="word" name="requestContent"><b>requestContent</b></td>
2194 <td>
2195 <p>This conversion word displays the content of the request,
2196 that is the request's <code>InputStream</code>. It is used
2197 in conjunction with a <a
2198 href="../xref/ch/qos/logback/access/servlet/TeeFilter.html">
2199 <code>TeeFilter</code></a>, a
2200 <code>javax.servlet.Filter</code> that replaces the original
2201 <code>HttpServletRequest</code> by a <a
2202 href="../xref/ch/qos/logback/access/servlet/TeeHttpServletRequest.html">
2203 <code>TeeHttpServletRequest</code></a>. The latter object
2204 allows access to the request's <code>InputStream</code>
2205 multiple times without any loss of data.
2206 </p>
2207 </td>
2208 </tr>
2209 <tr class="a">
2210 <td class="word" name="fullRequest"><b>fullRequest</b></td>
2211 <td>
2212 <p>This converter outputs the data associated with the
2213 request, including all headers and request contents.
2214 </p>
2215 </td>
2216 </tr>
2217 <tr class="b">
2218 <td class="word" name="responseContent"><b>responseContent</b></td>
2219 <td>
2220 <p>This conversion word displays the content of the
2221 response, that is the response's
2222 <code>InputStream</code>. It is used in conjunction with a
2223 <a href="../xref/ch/qos/logback/access/servlet/TeeFilter.html">
2224 <code>TeeFilter</code></a>, a
2225 <code>javax.servlet.Filter</code> that replaces the original
2226 <code>HttpServletResponse</code> by a <a
2227 href="../xref/ch/qos/logback/access/servlet/TeeHttpServletResponse.html">
2228 <code>TeeHttpServletResponse</code></a>. The latter object
2229 allows access to the request's <code>InputStream</code>
2230 multiple times without any loss of data.
2231 </p>
2232 </td>
2233 </tr>
2234 <tr class="a">
2235 <td class="word" name="fullResponse"><b>fullResponse</b></td>
2236 <td>
2237 <p>This conversion word takes all the available data
2238 associated with the response, including all headers of the
2239 response and response contents.
2240 </p>
2241 </td>
2242 </tr>
2243 </table>
2244
2245 <p>Logback access' <code>PatternLayout</code> also recognizes three keywords, which
2246 act like shortcuts.</p>
2247
2248 <table class="bodyTable">
2249 <tr>
2250 <th>keyword</th>
2251 <th>equivalent conversion pattern</th>
2252 </tr>
2253 <tr class="a">
2254 <td><em>common</em> or <em>CLF</em></td>
2255 <td><em>%h %l %u [%t] "%r" %s %b</em></td>
2256 </tr>
2257 <tr class="b">
2258 <td><em>combined</em></td>
2259 <td><em>%h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"</em></td>
2260 </tr>
2261
2262 </table>
2263
2264
2265 <p>The <em>common</em> keyword corresponds to the pattern <em>'%h %l %u [%t] "%r" %s %b'</em>
2266 which displays client host, remote log name, user, date, requested URL, status code
2267 and response's content length</p>
2268
2269 <p>The <em>combined</em> keyword is a shortcut for <em>'%h %l %u [%t]
2270 "%r" %s %b "%i{Referer}" "%i{User-Agent}"'</em>. This pattern
2271 begins much like the <em>common</em> pattern but also displays two
2272 request headers, namely referer, and user-agent.</p>
2273
2274 <h3 class="doAnchor" name="AccessHTMLLayout">HTMLLayout</h3>
2275
2276 <p>The <a
2277 href="../xref/ch/qos/logback/access/html/HTMLLayout.html"><code>HTMLLayout</code></a>
2278 class found in logback-access is similar to the <a
2279 href="#ClassicHTMLLayout"><code>HTMLLayout</code></a> class from
2280 logback-classic.
2281 </p>
2282
2283 <p>By default, it will create a table containing the following data:</p>
2284
2285 <ul>
2286 <li>Remote IP</li>
2287 <li>Date</li>
2288 <li>Request URL</li>
2289 <li>Status code</li>
2290 <li>Content Length</li>
2291 </ul>
2292
2293 <p>Here is a sample output produced by <code>HTMLLayout</code> in
2294 logback-access:</p>
2295 <img src="images/chapters/layouts/htmlLayoutAccess.gif" alt="Access HTML Layout Sample Image"/>
2296
2297 <p>What can be better than a real world example? Our own log4j
2298 properties for logback <a
2299 href="http://logback.qos.ch/translator/">translator</a> makes use
2300 of logback-access to demonstrate live output from
2301 <code>RollingFileAppender</code> with <code>HTMLLayout</code>.</p>
2302
2303
2304 <p>On every new user request to our <a
2305 href="http://logback.qos.ch/translator/">translator</a>
2306 web-application, a new entry will be added to the access logs,
2307 which you can view by <a
2308 href="http://logback.qos.ch/translator/logs/access.html">following
2309 this link</a>.</p>
2310
2311
2312 <script src="../templates/footer.js" type="text/javascript"></script>
2313 </div>
2314 </body>
2315 </html>