Debian Codegraph @

logback-site/src/site/pages/manual/architecture.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 2: Architecture</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 </head>
13 <body onload="prettyPrint(); decorate();">
14 <script type="text/javascript">prefix='../';</script>
15 <script type="text/javascript" src="../js/prettify.js"></script>
16 <script type="text/javascript" src="../templates/header.js"></script>
17 <script type="text/javascript" src="../js/jquery-min.js"></script>
18 <script type="text/javascript" src="../js/decorator.js"></script>
19 <div id="left">
20 <noscript>Please turn on Javascript to view this menu</noscript>
21 <script src="../templates/left.js" type="text/javascript"></script>
22 </div>
23 <div id="right">
24 <script src="menu.js" type="text/javascript"></script>
25 </div>
26 <div id="content">
27
28 <h1>Chapter 2: Architecture</h1>
29
30 <a href="architecture_ja.html">&#x548C;&#x8A33; (Japanese translation)</a>
31
32 <div class="quote">
33 <p><em>All true classification is genealogical.</em></p>
34 <p>&mdash;CHARLES DARWIN, <em>The Origin of Species</em></p>
35
36 <p><em>It is difficult, if not impossible, for anyone to learn a
37 subject purely by reading about it, without applying the
38 information to specific problems and thereby forcing himself to
39 think about what has been read. Furthermore, we all learn best
40 the things that we have discovered ourselves.</em>
41 </p>
42 <p>&mdash;DONALD KNUTH, <em>The Art of Computer Programming</em></p>
43 </div>
44
45
46 <script src="../templates/creative.js" type="text/javascript"></script>
47
48 <h2>Logback's architecture</h2>
49
50 <p>Logback's basic architecture is sufficiently generic so as to
51 apply under different circumstances. At the present time, logback
52 is divided into three modules, logback-core, logback-classic and
53 logback-access.
54 </p>
55
56 <p>The <em>core</em> module lays the groundwork for the other two
57 modules. The <em>classic</em> module extends <em>core</em>. The
58 classic module corresponds to a significantly improved version of
59 log4j. Logback-classic natively implements the <a
60 href="http://www.slf4j.org">SLF4J API</a> so that you can readily
61 switch back and forth between logback and other logging systems
62 such as log4j or java.util.logging (JUL) introduced in JDK
63 1.4. The third module called <em>access</em> integrates with
64 Servlet containers to provide HTTP-access log functionality. A
65 separate document covers <a href="../access.html">access module
66 documentation</a>.
67 </p>
68
69 <p>In the remainder of this document, we will write "logback" to
70 refer to the logback-classic module.
71 </p>
72
73 <h2>Logger, Appenders and Layouts</h2>
74
75 <p>Logback is built upon three main classes: <code>Logger</code>,
76 <code>Appender</code> and <code>Layout</code>. These three types
77 of components work together to enable developers to log messages
78 according to message type and level, and to control at runtime how
79 these messages are formatted and where they are reported.
80 </p>
81
82 <p>The <code>Logger</code> class is part of the logback-classic
83 module. On the other hand, the <code>Appender</code> and
84 <code>Layout</code> interfaces are part of logback-core. As a
85 general-purpose module, logback-core has no notion of
86 loggers.
87 </p>
88
89 <h3 class="doAnchor" name="LoggerContext">Logger context</h3>
90
91 <p>The first and foremost advantage of any logging API over plain
92 <code>System.out.println</code> resides in its ability to disable
93 certain log statements while allowing others to print
94 unhindered. This capability assumes that the logging space, that
95 is, the space of all possible logging statements, is categorized
96 according to some developer-chosen criteria. In logback-classic,
97 this categorization is an inherent part of loggers. Every single
98 logger is attached to a <code>LoggerContext</code> which is
99 responsible for manufacturing loggers as well as arranging them in
100 a tree like hierarchy.
101 </p>
102
103 <p>Loggers are named entities. Their names are case-sensitive and
104 they follow the hierarchical naming rule:
105 </p>
106
107 <div class="definition">
108 <div class="deftitle">Named Hierarchy</div>
109 <p>
110 A logger is said to be an ancestor of another logger if
111 its name followed by a dot is a prefix of the descendant
112 logger name. A logger is said to be a parent of a child
113 logger if there are no ancestors between itself and the
114 descendant logger.
115 </p>
116 </div>
117
118 <p>For example, the logger named <code>"com.foo"</code> is a
119 parent of the logger named <code>"com.foo.Bar"</code>. Similarly,
120 <code>"java"</code> is a parent of <code>"java.util"</code> and an
121 ancestor of <code>"java.util.Vector"</code>. This naming scheme
122 should be familiar to most developers.
123 </p>
124
125 <p>The root logger resides at the top of the logger hierarchy. It
126 is exceptional in that it is part of every hierarchy at its
127 inception. Like every logger, it can be retrieved by its name, as
128 follows:
129 </p>
130
131 <pre class="prettyprint source">Logger rootLogger = LoggerFactory.getLogger(<a
132 href="http://www.slf4j.org/apidocs/constant-values.html#org.slf4j.Logger.ROOT_LOGGER_NAME">org.slf4j.Logger.ROOT_LOGGER_NAME</a>);</pre>
133
134 <p>All other loggers are also retrieved with the class static
135 <code>getLogger</code> method found in the <a
136 href="http://www.slf4j.org/api/org/slf4j/Logger.html">org.slf4j.LoggerFactory</a>
137 class. This method takes the name of the desired logger as a
138 parameter. Some of the basic methods in the <code>Logger</code>
139 interface are listed below.
140 </p>
141
142 <pre class="prettyprint source">package org.slf4j;
143 public interface Logger {
144
145 // Printing methods:
146 public void trace(String message);
147 public void debug(String message);
148 public void info(String message);
149 public void warn(String message);
150 public void error(String message);
151 }</pre>
152
153
154
155 <h3 class="doAnchor" name="effectiveLevel">Effective Level aka
156 Level Inheritance </h3>
157
158 <p>Loggers may be assigned levels. The set of possible levels
159 (TRACE, DEBUG, INFO, WARN and ERROR) are defined in the
160 <code>ch.qos.logback.classic.Level</code> class. Note that in
161 logback, the <code>Level</code> class is final and cannot be
162 sub-classed, as a much more flexible approach exists in the form
163 of <code>Marker</code> objects.
164 </p>
165
166 <p>If a given logger is not assigned a level, then it inherits one
167 from its closest ancestor with an assigned level. More formally:
168 </p>
169
170 <div class="definition">
171
172
173 <p>The effective level for a given logger <em>L</em>, is equal
174 to the first non-null level in its hierarchy, starting at
175 <em>L</em> itself and proceeding upwards in the hierarchy
176 towards the root logger.
177 </p>
178 </div>
179
180 <p>To ensure that all loggers can eventually inherit a level, the
181 root logger always has an assigned level. By default, this level
182 is DEBUG.
183 </p>
184
185 <p>Below are four examples with various assigned level values and
186 the resulting effective (inherited) levels according to the level
187 inheritance rule.
188 </p>
189
190 <em>Example 1</em>
191 <table class="bodyTable">
192 <tr>
193 <th>Logger name</th>
194 <th>Assigned level</th>
195 <th>Effective level</th>
196 </tr>
197 <tr class="alt">
198 <td>root</td>
199 <td>DEBUG</td>
200 <td>DEBUG</td>
201 </tr>
202 <tr>
203 <td>X</td>
204 <td>none</td>
205 <td>DEBUG</td>
206 </tr>
207
208 <tr class="alt">
209 <td>X.Y</td>
210 <td>none</td>
211 <td>DEBUG</td>
212 </tr>
213 <tr>
214 <td>X.Y.Z</td>
215 <td>none</td>
216 <td>DEBUG</td>
217 </tr>
218 </table>
219
220 <p> In example 1 above, only the root logger is assigned a level.
221 This level value, <code>DEBUG</code>, is inherited by the other
222 loggers <code>X</code>, <code>X.Y</code> and <code>X.Y.Z</code>
223 </p>
224
225 <em>Example 2</em>
226 <table class="bodyTable">
227 <tr>
228 <th>Logger name</th>
229 <th>Assigned level</th>
230 <th>Effective level</th>
231 </tr>
232 <tr class="alt" align="left">
233 <td>root</td>
234 <td>ERROR</td>
235 <td>ERROR</td>
236 </tr>
237 <tr align="left">
238 <td>X</td>
239 <td>INFO</td>
240 <td>INFO</td>
241 </tr>
242
243 <tr class="alt" align="left">
244 <td>X.Y</td>
245 <td>DEBUG</td>
246 <td>DEBUG</td>
247 </tr>
248 <tr align="left">
249 <td>X.Y.Z</td>
250 <td>WARN</td>
251 <td>WARN</td>
252 </tr>
253 </table>
254
255 <p>In example 2 above, all loggers have an assigned level value.
256 Level inheritance does not come into play.
257 </p>
258
259 <em>Example 3</em>
260 <table class="bodyTable">
261 <tr>
262 <th>Logger name</th>
263 <th>Assigned level</th>
264 <th>Effective level</th>
265 </tr>
266 <tr class="alt" align="left">
267 <td>root</td>
268 <td>DEBUG</td>
269 <td>DEBUG</td>
270 </tr>
271
272 <tr align="left">
273 <td>X</td>
274 <td>INFO</td>
275 <td>INFO</td>
276 </tr>
277 <tr class="alt" align="left">
278 <td>X.Y</td>
279 <td>none</td>
280 <td>INFO</td>
281 </tr>
282 <tr align="left">
283 <td>X.Y.Z</td>
284 <td>ERROR</td>
285 <td>ERROR</td>
286 </tr>
287 </table>
288
289 <p>In example 3 above, the loggers <code>root</code>,
290 <code>X</code> and <code>X.Y.Z</code> are assigned the levels
291 <code>DEBUG</code>, <code>INFO</code> and <code>ERROR</code>
292 respectively. Logger <code>X.Y</code> inherits its level value
293 from its parent <code>X</code>.
294 </p>
295
296 <em>Example 4</em>
297 <table class="bodyTable">
298
299 <tr>
300 <th>Logger name</th>
301 <th>Assigned level</th>
302 <th>Effective level</th>
303 </tr>
304 <tr class="alt" align="left">
305 <td>root</td>
306 <td>DEBUG</td>
307 <td>DEBUG</td>
308 </tr>
309
310 <tr align="left">
311 <td>X</td>
312 <td>INFO</td>
313 <td>INFO</td>
314 </tr>
315 <tr class="alt" align="left">
316 <td>X.Y</td>
317 <td>none</td>
318 <td>INFO</td>
319 </tr>
320 <tr align="left">
321 <td>X.Y.Z</td>
322 <td>none</td>
323 <td>INFO</td>
324 </tr>
325 </table>
326
327
328 <p>In example 4 above, the loggers <code>root</code> and
329 <code>X</code> and are assigned the levels <code>DEBUG</code> and
330 <code>INFO</code> respectively. The loggers <code>X.Y</code> and
331 <code>X.Y.Z</code> inherit their level value from their nearest
332 parent <code>X</code>, which has an assigned level.
333 </p>
334
335 <h3 class="doAnchor" name="basic_selection">Printing methods and
336 the basic selection rule</h3>
337
338 <p>By definition, the printing method determines the level of a
339 logging request. For example, if <code>L</code> is a logger
340 instance, then the statement <code>L.info("..")</code> is a
341 logging statement of level INFO.
342 </p>
343
344
345 <p>A logging request is said to be <em>enabled</em> if its level
346 is higher than or equal to the effective level of its
347 logger. Otherwise, the request is said to be <em>disabled</em>. As
348 described previously, a logger without an assigned level will
349 inherit one from its nearest ancestor. This rule is summarized
350 below.
351 </p>
352
353
354 <div class="definition">
355 <div class="deftitle">Basic Selection Rule</div>
356
357 <p>A log request of level <em>p</em> issued to a logger having
358 an effective level <em>q</em>, is enabled if
359 <em>p&nbsp;&gt;=&nbsp;q</em>.
360 </p>
361 </div>
362
363 <p>This rule is at the heart of logback. It assumes that levels
364 are ordered as follows:
365 <code>TRACE&nbsp;&lt;&nbsp;DEBUG&nbsp;&lt;&nbsp;INFO&nbsp;&lt;
366 &nbsp;WARN&nbsp;&lt;&nbsp;ERROR</code>.
367 </p>
368
369 <p>In a more graphic way, here is how the selection rule works. In
370 the following table, the vertical header shows the level of
371 the logging request, designated by <em>p</em>, while the
372 horizontal header shows effective level of the logger, designated
373 by <em>q</em>. The intersection of the rows (level request) and
374 columns (effective level) is the boolean resulting from the basic
375 selection rule.
376 </p>
377
378 <table width="80%">
379 <tr>
380 <td class="lgray_bg" rowspan="2">level of <br/>request <em>p</em></td>
381 <td style="border-top: 1px solid #DDDDDD;"
382 align="center" colspan="6">effective level <em>q</em></td>
383 </tr>
384 <tr align="left">
385 <th style="border-bottom: 1px solid #DDDDDD;">TRACE</th>
386 <th style="border-bottom: 1px solid #DDDDDD;">DEBUG</th>
387 <th style="border-bottom: 1px solid #DDDDDD;">INFO</th>
388 <th style="border-bottom: 1px solid #DDDDDD;">WARN</th>
389 <th style="border-bottom: 1px solid #DDDDDD;">ERROR</th>
390 <th style="border-bottom: 1px solid #DDDDDD;">OFF</th>
391 </tr>
392 <tr align="left" >
393 <th class="lgray_bg">TRACE</th>
394 <td><span class="greenBold">YES</span></td>
395 <td><span class="redBold">NO</span></td>
396 <td><span class="redBold">NO</span></td>
397 <td><span class="redBold">NO</span></td>
398 <td><span class="redBold">NO</span></td>
399 <td><span class="redBold">NO</span></td>
400 </tr>
401
402 <tr align="left">
403 <th class="lgray_bg">DEBUG</th>
404 <td><span class="greenBold">YES</span></td>
405 <td><span class="greenBold">YES</span></td>
406 <td><span class="redBold">NO</span></td>
407 <td><span class="redBold">NO</span></td>
408 <td><span class="redBold">NO</span></td>
409 <td><span class="redBold">NO</span></td>
410 </tr>
411 <tr align="left" >
412 <th class="lgray_bg">INFO</th>
413 <td><span class="greenBold">YES</span></td>
414 <td><span class="greenBold">YES</span></td>
415 <td><span class="greenBold">YES</span></td>
416 <td><span class="redBold">NO</span></td>
417 <td><span class="redBold">NO</span></td>
418 <td><span class="redBold">NO</span></td>
419 </tr>
420 <tr align="left" >
421 <th class="lgray_bg">WARN</th>
422 <td><span class="greenBold">YES</span></td>
423 <td><span class="greenBold">YES</span></td>
424 <td><span class="greenBold">YES</span></td>
425 <td><span class="greenBold">YES</span></td>
426 <td><span class="redBold">NO</span></td>
427 <td><span class="redBold">NO</span></td>
428 </tr>
429 <tr align="left" >
430 <th class="lgray_bg">ERROR</th>
431 <td><span class="greenBold">YES</span></td>
432 <td><span class="greenBold">YES</span></td>
433 <td><span class="greenBold">YES</span></td>
434 <td><span class="greenBold">YES</span></td>
435 <td><span class="greenBold">YES</span></td>
436 <td><span class="redBold">NO</span></td>
437 </tr>
438 </table>
439
440 <p>Here is an example of the basic selection rule.</p>
441
442 <pre class="prettyprint source">import ch.qos.logback.classic.Level;
443 import org.slf4j.Logger;
444 import org.slf4j.LoggerFactory;
445 ....
446
447 // get a logger instance named "com.foo". Let us further assume that the
448 // logger is of type ch.qos.logback.classic.Logger so that we can
449 // set its level
450 ch.qos.logback.classic.Logger logger =
451 (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.foo");
452 //set its Level to <span class="blue">INFO</span>. The setLevel() method requires a logback logger
453 logger.setLevel(Level. <span class="blue">INFO</span>);
454
455 Logger barlogger = LoggerFactory.getLogger("com.foo.Bar");
456
457 // This request is enabled, because <span class="green bold">WARN</span> &gt;= <span class="blue">INFO</span>
458 logger.<span class="green bold">warn</span>("Low fuel level.");
459
460 // This request is disabled, because <span class="green bold">DEBUG</span> &lt; <span class="blue">INFO</span>.
461 logger.<span class="green bold">debug</span>("Starting search for nearest gas station.");
462
463 // The logger instance barlogger, named "com.foo.Bar",
464 // will inherit its level from the logger named
465 // "com.foo" Thus, the following request is enabled
466 // because <span class="green bold">INFO</span> &gt;= <span class="blue">INFO</span>.
467 barlogger.<span class="green bold">info</span>("Located nearest gas station.");
468
469 // This request is disabled, because <span class="green bold">DEBUG</span> &lt; <span class="blue">INFO</span>.
470 barlogger.<span class="green bold">debug</span>("Exiting gas station search");</pre>
471
472 <a name="RetrievingLoggers"></a>
473 <h3>Retrieving Loggers</h3>
474 <p>
475 Calling the <code><a href="../apidocs/org/slf4j/LoggerFactory.html#getLogger(java.lang.String)">LoggerFactory.getLogger</a></code>
476 method with the same name will always return a reference to
477 the exact same logger object.
478 </p>
479
480 <p>For example, in</p>
481 <pre class="prettyprint source">Logger x = LoggerFactory.getLogger("wombat");
482 Logger y = LoggerFactory.getLogger("wombat");</pre>
483
484 <p>
485 <code>x</code> and <code>y</code> refer to
486 <em>exactly</em> the same logger object.
487 </p>
488
489 <p>Thus, it is possible to configure a logger and then to retrieve
490 the same instance somewhere else in the code without passing
491 around references. In fundamental contradiction to biological
492 parenthood, where parents always precede their children, logback
493 loggers can be created and configured in any order. In particular,
494 a "parent" logger will find and link to its descendants even if it
495 is instantiated after them.
496 </p>
497 <p>Configuration of the logback environment is typically done at
498 application initialization. The preferred way is by reading a
499 configuration file. This approach will be discussed shortly.
500 </p>
501 <p>Logback makes it easy to name loggers by <em>software
502 component</em>. This can be accomplished by instantiating a
503 logger in each class, with the logger name equal to the fully
504 qualified name of the class. This is a useful and straightforward
505 method of defining loggers. As the log output bears the name of
506 the generating logger, this naming strategy makes it easy to
507 identify the origin of a log message. However, this is only one
508 possible, albeit common, strategy for naming loggers. Logback does
509 not restrict the possible set of loggers. As a developer, you are
510 free to name loggers as you wish.
511 </p>
512
513 <p>Nevertheless, naming loggers after the class where they are
514 located seems to be the best general strategy known so far.
515 </p>
516
517 <a name="AppendersAndLayouts"></a>
518 <h3>Appenders and Layouts</h3>
519
520 <p>The ability to selectively enable or disable logging requests
521 based on their logger is only part of the picture. Logback allows
522 logging requests to print to multiple destinations. In logback
523 speak, an output destination is called an appender. Currently,
524 appenders exist for the console, files, remote socket servers, to
525 MySQL, PostgreSQL, Oracle and other databases, JMS, and remote
526 UNIX Syslog daemons.
527
528 <!--It is also possible to log asynchronously. -->
529 </p>
530
531 <p>More than one appender can be attached to a logger.</p>
532
533 <p>The <code><a
534 href="../apidocs/ch/qos/logback/classic/Logger.html#addAppender(ch.qos.logback.core.Appender)">addAppender</a></code>
535 method adds an appender to a given logger. Each enabled logging
536 request for a given logger will be forwarded to all the appenders
537 in that logger as well as the appenders higher in the
538 hierarchy. In other words, appenders are inherited additively from
539 the logger hierarchy. For example, if a console appender is added
540 to the root logger, then all enabled logging requests will at
541 least print on the console. If in addition a file appender is
542 added to a logger, say <em>L</em>, then enabled logging requests
543 for <em>L</em> and <em>L</em>'s children will print on a file
544 <em>and</em> on the console. It is possible to override this
545 default behavior so that appender accumulation is no longer
546 additive by setting the additivity flag of a logger to false.
547 </p>
548
549 <p>The rules governing appender additivity are summarized below.
550 </p>
551 <div class="definition">
552
553 <h4 class="deftitle"><a name="additivity"
554 href="#additivity"><span class="anchor"/></a>Appender
555 Additivity</h4>
556
557 <p>The output of a log statement of logger <em>L</em> will go to
558 all the appenders in <em>L</em> and its ancestors. This is the
559 meaning of the term "appender additivity".
560 </p>
561
562 <p>However, if an ancestor of logger <em>L</em>, say <em>P</em>,
563 has the additivity flag set to false, then <em>L</em>'s output
564 will be directed to all the appenders in <em>L</em> and its
565 ancestors up to and including <em>P</em> but not the appenders in
566 any of the ancestors of <em>P</em>.
567 </p>
568
569 <p>Loggers have their additivity flag set to true by default.
570 </p>
571
572 </div>
573 The table below shows an example:
574
575 <table class="bodyTable">
576 <tr>
577 <th>Logger Name</th>
578 <th>Attached Appenders</th>
579 <th>Additivity Flag</th>
580 <th>Output Targets</th>
581 <th>Comment</th>
582 </tr>
583 <tr>
584 <td>root</td>
585 <td>A1</td>
586 <td>not applicable</td>
587 <td>A1</td>
588
589 <td>Since the root logger stands at the top of the logger
590 hierarchy, the additivity flag does not apply to it.
591 </td>
592 </tr>
593 <tr class="alt">
594 <td>x</td>
595 <td>A-x1, A-x2</td>
596 <td>true</td>
597 <td>A1, A-x1, A-x2</td>
598 <td>Appenders of "x" and of root.</td>
599 </tr>
600 <tr>
601 <td>x.y</td>
602 <td>none</td>
603 <td>true</td>
604 <td>A1, A-x1, A-x2</td>
605 <td>Appenders of "x" and of root.</td>
606 </tr>
607 <tr class="alt">
608 <td>x.y.z</td>
609 <td>A-xyz1</td>
610 <td>true</td>
611 <td>A1, A-x1, A-x2, A-xyz1</td>
612 <td>Appenders of "x.y.z", "x" and of root.</td>
613 </tr>
614 <tr>
615 <td>security</td>
616 <td>A-sec</td>
617 <td class="blue"><span class="blue">false</span></td>
618 <td>A-sec</td>
619
620 <td>
621 No appender accumulation since the additivity flag is set to
622 <code>false</code>. Only appender A-sec will be used.
623 </td>
624 </tr>
625 <tr class="alt">
626 <td>security.access</td>
627 <td>none</td>
628 <td>true</td>
629 <td>A-sec</td>
630 <td>
631 Only appenders of "security" because the additivity
632 flag in "security" is set to
633 <code>false</code>.
634 </td>
635 </tr>
636 </table>
637
638
639 <p>More often than not, users wish to customize not only the
640 output destination but also the output format. This is
641 accomplished by associating a <em>layout</em> with an
642 appender. The layout is responsible for formatting the logging
643 request according to the user's wishes, whereas an appender takes
644 care of sending the formatted output to its destination. The
645 <code>PatternLayout</code>, part of the standard logback
646 distribution, lets the user specify the output format according to
647 conversion patterns similar to the C language <code>printf</code>
648 function.
649 </p>
650
651 <p>For example, the PatternLayout with the conversion pattern
652 "%-4relative [%thread] %-5level %logger{32} - %msg%n" will output
653 something akin to:
654 </p>
655
656 <div class="prettyprint source"><pre>176 [main] DEBUG manual.architecture.HelloWorld2 - Hello world.</pre></div>
657
658 <p>The first field is the number of milliseconds elapsed since the
659 start of the program. The second field is the thread making the
660 log request. The third field is the level of the log request. The
661 fourth field is the name of the logger associated with the log
662 request. The text after the '-' is the message of the request.
663 </p>
664
665
666 <h3 class="doAnchor" name="parametrized">Parameterized
667 logging</h3>
668
669 <p>Given that loggers in logback-classic implement the <a
670 href="http://www.slf4j.org/api/org/slf4j/Logger.html">SLF4J's
671 Logger interface</a>, certain printing methods admit more than one
672 parameter. These printing method variants are mainly intended to
673 improve performance while minimizing the impact on the readability
674 of the code.
675 </p>
676
677 <p>For some Logger <code>logger</code>, writing,</p>
678
679 <pre class="prettyprint source">logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));</pre>
680
681 <p>incurs the cost of constructing the message parameter, that is
682 converting both integer <code>i</code> and <code>entry[i]</code>
683 to a String, and concatenating intermediate strings. This is
684 regardless of whether the message will be logged or not.
685 </p>
686
687 <p>One possible way to avoid the cost of parameter construction is
688 by surrounding the log statement with a test. Here is an example.
689 </p>
690
691 <pre class="prettyprint source">if(logger.isDebugEnabled()) {
692 logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
693 }</pre>
694
695
696 <p>This way you will not incur the cost of parameter construction
697 if debugging is disabled for <code>logger</code>. On the other
698 hand, if the logger is enabled for the DEBUG level, you will incur
699 the cost of evaluating whether the logger is enabled or not,
700 twice: once in <code>debugEnabled</code> and once in
701 <code>debug</code>. In practice, this overhead is insignificant
702 because evaluating a logger takes less than 1% of the time it
703 takes to actually log a request.
704 </p>
705
706 <h4>Better alternative</h4>
707
708 <p>There exists a convenient alternative based on message
709 formats. Assuming <code>entry</code> is an object, you can write:
710 </p>
711
712
713 <pre class="prettyprint source">Object entry = new SomeObject();
714 logger.debug("The entry is {}.", entry);</pre>
715
716 <p>Only after evaluating whether to log or not, and only if the decision
717 is positive, will the logger implementation format the message and
718 replace the '{}' pair with the string value of <code>entry</code>.
719 In other words, this form does not incur the cost of parameter
720 construction when the log statement is disabled.
721 </p>
722
723
724 <p>The following two lines will yield the exact same output.
725 However, in case of a <em>disabled</em> logging statement, the
726 second variant will outperform the first variant by a factor of at
727 least 30.
728 </p>
729
730 <pre class="prettyprint source">logger.debug("The new entry is "+entry+".");
731 logger.debug("The new entry is {}.", entry);</pre>
732
733
734 <p>A two argument variant is also available. For example, you can
735 write:
736 </p>
737
738 <pre class="prettyprint source">logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);</pre>
739
740 <p>If three or more arguments need to be passed, an
741 <code>Object[]</code> variant is also available. For example, you
742 can write:
743 </p>
744
745
746 <pre class="prettyprint source">Object[] paramArray = {newVal, below, above};
747 logger.debug("Value {} was inserted between {} and {}.", paramArray);</pre>
748
749
750 <a name="UnderTheHood"></a>
751 <h3>A peek under the hood</h3>
752
753 <p>After we have introduced the essential logback components, we are
754 now ready to describe the steps that the logback framework takes
755 when the user invokes a logger's printing method. Let us now analyze
756 the steps logback takes when the user invokes the
757 <code>info()</code> method of a logger named <em>com.wombat</em>.
758 </p>
759
760 <h4>1. Get the filter chain decision</h4>
761
762 <p>If it exists, the <code>TurboFilter</code> chain is
763 invoked. Turbo filters can set a context-wide threshold, or filter
764 out certain events based on information such as <code>Marker</code>,
765 <code>Level</code>, <code>Logger</code>, message, or the
766 <code>Throwable</code> that are associated with each logging
767 request. If the reply of the filter chain is
768 <code>FilterReply.DENY</code>, then the logging request is
769 dropped. If it is <code>FilterReply.NEUTRAL</code>, then we continue
770 with the next step, i.e. step 2. In case the reply is
771 <code>FilterReply.ACCEPT</code>, we skip the next and directly jump
772 to step 3.
773 </p>
774
775 <h4>2. Apply the <a href="#basic_selection">basic selection
776 rule</a></h4>
777
778 <p>At this step, logback compares the effective level of the logger
779 with the level of the request. If the logging request is disabled
780 according to this test, then logback will drop the request without
781 further processing. Otherwise, it proceeds to the next step.
782 </p>
783
784 <h4>3. Create a <code>LoggingEvent</code> object</h4>
785
786 <p>If the request survived the previous filters, logback will
787 create a <code>ch.qos.logback.classic.LoggingEvent</code> object
788 containing all the relevant parameters of the request, such as the
789 logger of the request, the request level, the message itself, the
790 exception that might have been passed along with the request, the
791 current time, the current thread, various data about the class that
792 issued the logging request and the <code>MDC</code>. Note that some
793 of these fields are initialized lazily, that is only when they are
794 actually needed. The <code>MDC</code> is used to decorate the
795 logging request with additional contextual information. MDC is
796 discussed in a <a href="mdc.html">subsequent chapter</a>.</p>
797
798 <h4>4. Invoking appenders</h4>
799
800 <p>After the creation of a <code>LoggingEvent</code> object, logback
801 will invoke the <code>doAppend()</code> methods of all the
802 applicable appenders, that is, the appenders inherited from the
803 logger context.
804 </p>
805
806 <p>All appenders shipped with the logback distribution extend the
807 <code>AppenderBase</code> abstract class that implements the
808 <code>doAppend</code> method in a synchronized block ensuring
809 thread-safety. The <code>doAppend()</code> method of
810 <code>AppenderBase</code> also invokes custom filters attached to
811 the appender, if any such filters exist. Custom filters, which can
812 be dynamically attached to any appender, are presented in a <a
813 href="filters.html">separate chapter</a>.
814 </p>
815
816 <h4>5. Formatting the output</h4>
817
818 <p>It is responsibility of the invoked appender to format the
819 logging event. However, some (but not all) appenders delegate the
820 task of formatting the logging event to a layout. A layout formats
821 the <code>LoggingEvent</code> instance and returns the result as a
822 String. Note that some appenders, such as the
823 <code>SocketAppender</code>, do not transform the logging event into
824 a string but serialize it instead. Consequently, they do not
825 have nor require a layout.
826 </p>
827
828 <h4>6. Sending out the <code>LoggingEvent</code></h4>
829
830 <p>After the logging event is fully formatted it is sent to its
831 destination by each appender.
832 </p>
833
834 <p>
835 Here is a sequence UML diagram to show how everything works. You might
836 want to click on the image to display its bigger version.
837 </p>
838
839 <a href="underTheHood.html">
840 <img src="images/chapters/architecture/underTheHoodSequence2_small.gif"
841 alt="underTheHoodSequence2_small.gif"/>
842 </a>
843
844
845 <h3 class="doAnchor" name="performance">Performance</h3>
846
847 <p>One of the often-cited arguments against logging is its
848 computational cost. This is a legitimate concern as even
849 moderately-sized applications can generate thousands of log
850 requests. Much of our development effort is spent measuring and
851 tweaking logback's performance. Independently of these efforts, the
852 user should still be aware of the following performance issues.
853 </p>
854
855 <h4>1. Logging performance when logging is turned off entirely</h4>
856
857 <p>You can turn off logging entirely by setting the level of the
858 root logger to <code>Level.OFF</code>, the highest possible level.
859 When logging is turned off entirely, the cost of a log request
860 consists of a method invocation plus an integer comparison. On a
861 3.2Ghz Pentium D machine this cost is typically around 20
862 nanoseconds.
863 </p>
864
865 <p>However, any method invocation involves the "hidden" cost of
866 parameter construction. For example, for some logger <em>x</em>
867 writing,
868 </p>
869
870 <pre class="prettyprint source">x.debug("Entry number: " + i + "is " + entry[i]);</pre>
871
872 <p>incurs the cost of constructing the message parameter,
873 i.e. converting both integer <code>i</code> and
874 <code>entry[i]</code> to a string, and concatenating intermediate
875 strings, regardless of whether the message will be logged or not.
876 </p>
877
878 <p>The cost of parameter construction can be quite high and depends
879 on the size of the parameters involved. To avoid the cost of
880 parameter construction you can take advantage of SLF4J's parameterized
881 logging:
882 </p>
883
884 <pre class="prettyprint source">x.debug("Entry number: {} is {}", i, entry[i]);</pre>
885
886 <p>This variant will not incur the cost of parameter
887 construction. Compared to the previous call to the
888 <code>debug()</code> method, it will be faster by a wide margin.
889 The message will be formatted only if the logging request is to be
890 sent to attached appenders. Moreover, the component that formats
891 messages is highly optimized.
892 </p>
893
894 <p>Notwithstanding the above placing log statements in tight loops,
895 i.e. very frequently invoked code, is a lose-lose proposal, likely
896 to result in degraded performance. Logging in tight loops will slow
897 down your application even if logging is turned off, and if logging
898 is turned on, will generate massive (and hence useless) output.
899 </p>
900
901 <h4>2. The performance of deciding whether to log or not to log when
902 logging is turned on.</h4>
903
904 <p>In logback, there is no need to walk the logger hierarchy. A
905 logger knows its effective level (that is, its level, once level
906 inheritance has been taken into consideration) when it is
907 created. Should the level of a parent logger be changed, then all
908 child loggers are contacted to take notice of the change. Thus,
909 before accepting or denying a request based on the effective level,
910 the logger can make a quasi-instantaneous decision, without needing
911 to consult its ancestors.
912 </p>
913
914
915 <h4>3. Actual logging (formatting and writing to the output device)</h4>
916
917 <p>This is the cost of formatting the log output and sending it to
918 its target destination. Here again, a serious effort was made to
919 make layouts (formatters) perform as quickly as possible. The same
920 is true for appenders. The typical cost of actually logging is about
921 9 to 12 microseconds when logging to a file on the local machine.
922 It goes up to several milliseconds when logging to a database on a
923 remote server.
924 </p>
925
926 <p>Although feature-rich, one of the foremost design goals of
927 logback was speed of execution, a requirement which is second only
928 to reliability. Some logback components have been rewritten several
929 times to improve performance.
930 </p>
931
932
933 <script src="../templates/footer.js" type="text/javascript"></script>
934 </div>
935 </body>
936 </html>