Debian Codegraph @

logback-site/src/site/pages/manual/groovy.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>Chapter12: Groovy configuration</title>
8
9 <link rel="stylesheet" type="text/css" href="../css/common.css" />
10 <link rel="stylesheet" type="text/css" href="../css/screen.css" media="screen" />
11 <link rel="stylesheet" type="text/css" href="../css/_print.css" media="print" />
12 <link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen" />
13
14 </head>
15 <body onload="prettyPrint(); decorate();">
16
17 <script type="text/javascript">prefix='../'</script>
18 <script type="text/javascript" src="../js/prettify.js"></script>
19 <script type="text/javascript" src="../js/dsl.js"></script>
20 <script type="text/javascript" src="../templates/header.js"></script>
21 <script type="text/javascript" src="../js/jquery-min.js"></script>
22 <script type="text/javascript" src="../js/decorator.js"></script>
23
24 <div id="left">
25 <noscript>Please turn on Javascript to view this menu</noscript>
26 <script src="../templates/left.js" type="text/javascript"></script>
27 </div>
28 <div id="right">
29 <script src="menu.js" type="text/javascript"></script>
30 </div>
31 <div id="content" class="chapter">
32
33 <h1>Chapter 12: Groovy Configuration</h1>
34
35 <a href="groovy_ja.html">&#x548C;&#x8A33; (Japanese translation)</a>
36
37
38 <div class="quote">
39 <p><em>It is better to be a human being dissatisfied than a pig
40 satisfied; better to be a Socrates dissatisfied than a fool
41 satisfied. And if the fool or the pig thinks otherwise, it is
42 because they have no experience of the better part.
43 </em>
44 </p>
45 <p>&mdash;JOHN STUART MILL, <em>Utilitarianism</em></p>
46 </div>
47 <script src="../templates/creative.js" type="text/javascript"></script>
48
49
50 <p>Domain-specific languages or DSLs are rather pervasive. The
51 XML-based logback configuration can be viewed as a DSL
52 instance. By the very nature of XML, XML-based configuration files
53 are quite verbose and rather bulky. Moreover, a relatively large
54 body of code in logback, namely Joran, is dedicated to processing
55 these XML-based configuration files. Joran supports nifty features
56 such as variable substitution, conditional processing and
57 on-the-fly extensibility. However, not only is Joran a complex
58 beast, the user-experience it provides can be described as
59 unsatisfactory or at the very least unintuitive.
60 </p>
61
62 <p>The Groovy-based DSL described in this chapter aims to be
63 consistent, intuitive, and powerful. Everything you can do using XML in
64 configuration files, you can do in Groovy with a much shorter
65 syntax. To help you migrate to Groovy style configuration, we have
66 developed a <a
67 href="http://logback.qos.ch/translator/asGroovy.html">tool to
68 automatically migrate your existing <em>logback.xml</em> files to
69 <em>logback.groovy</em></a>.
70 </p>
71
72
73 <h2 class="doAnchor">General philosophy</h2>
74
75 <p>As a general rule, <em>logback.groovy</em> files are Groovy
76 programs. And since Groovy is a super-set of Java, whatever
77 configuration actions you can perform in Java, you can do the same
78 within a <em>logback.groovy</em> file. However, since configuring
79 logback programmatically using Java syntax can be cumbersome, we
80 added a few logback-specific extensions to make your life
81 easier. We try hard to limit the number of logback-specific
82 syntactic extensions to an absolute minimum. If you are already
83 familiar with Groovy, you should be able to read, understand and
84 even write your own <em>logback.groovy</em> files with great
85 ease. Those unfamiliar with Groovy should still find
86 <em>logback.groovy</em> syntax much more comfortable to use than
87 <em>logback.xml</em>.
88 </p>
89
90 <p>Given that <em>logback.groovy</em> files are Groovy programs
91 with minimal logback-specific extensions, <em>all</em> the usual
92 groovy constructs such as class imports, variable definitions,
93 evaluation of $&#123;..&#125; expressions contained in strings
94 (GStrings), and if-else statements are available in
95 <em>logback.groovy</em> files.</p>
96
97 <h2 class="doAnchor">Automatic imports</h2>
98
99 <p><span class="label">Since 1.0.10</span> In order to reduce
100 unnecessary boilerplate several common types and packages are
101 imported automatically. Thus, as long as you are only configuring
102 built-in appenders, layouts etc. you do not need to add the
103 corresponding import statement into your script. You will need
104 them for types not covered by the default imports, of course.</p>
105
106 <p>Here is the list of default imports:</p>
107
108 <ul>
109 <li><span class="code">import ch.qos.logback.core.*;</span></li>
110 <li><span class="code">import ch.qos.logback.core.encoder.*;</span></li>
111 <li><span class="code">import ch.qos.logback.core.read.*;</span></li>
112 <li><span class="code">import ch.qos.logback.core.rolling.*;</span></li>
113 <li><span class="code">import ch.qos.logback.core.status.*;</span></li>
114 <li><span class="code">import ch.qos.logback.classic.net.*;</span></li>
115 <li><span class="code">import ch.qos.logback.classic.encoder.PatternLayoutEncoder;</span></li>
116 </ul>
117
118 <p>In addition, all constants in <span
119 class="code">ch.qos.logback.classic.Level</span> are statically
120 imported as is (uppercase) and as lowercased aliases. It follows
121 that your scripts can reference both <em>INFO</em> or
122 <em>info</em> without a static import statement.</p>
123
124
125 <h2 class="doAnchor" name="sift">SiftingAppender no longer supported</h2>
126
127 <p><span class="label">Since version 1.0.12</span>
128 <code>SiftingAppender</code> is no longer supported within groovy
129 configuration files. However, in case there is demand, it may be
130 re-introduced.</p>
131
132 <h2 class="doAnchor" name="entensions">Extensions specific to
133 <em>logback.groovy</em></h2>
134
135 <p><span class="green">Essentially, <em>Logback.groovy</em> syntax
136 consists of half a dozen methods described next; in the reverse
137 order of their customary appearance. </span>Strictly speaking, the
138 order of invocation of these methods does NOT matter, with one
139 exception: appenders MUST be defined before they can be attached
140 to a logger.</p>
141
142
143
144 <!-- ========================================================== -->
145
146 <h3> &#8226; <span class="code">root(Level level, List&lt;String> appenderNames = [])</span></h3>
147
148 <p>The <code>root</code> method can be used to set the level of
149 the root logger. As an optional second argument of type
150 <code>List&lt;String></code>, can be used to attach previously
151 defined appenders by name. If you do not specify the list of
152 appender names, then an empty list is assumed. In Groovy, an empty
153 list is denoted by <code>[]</code>.</p>
154
155 <p>To set the level of the root logger to WARN, you would write:</p>
156
157 <pre class="prettyprint source">root(WARN)</pre>
158
159 <p>To set the level of the root logger to INFO, and attach
160 appenders named "CONSOLE" and "FILE" to root, you would write:</p>
161
162 <pre class="prettyprint source">root(INFO, ["CONSOLE", "FILE"])</pre>
163
164 <p>In the previous example, it is assumed that the appenders named
165 "CONSOLE" and "FILE" were already defined. Defining appenders will
166 be discussed shortly.
167 </p>
168
169 <!-- ========================================================== -->
170
171 <h3>&#8226; <span class="code">logger(String name, Level level, List&lt;String> appenderNames = [], <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Boolean additivity = null)</span></h3>
172
173 <p>The <code>logger()</code> method takes four arguments, of which
174 the last two are optional. The first argument is the name of the
175 logger to configure. The second argument is the level of the
176 designated logger. Setting the level of a logger to
177 <code>null</code> forces it to <a
178 href="architecture.html#effectiveLevel">inherit its level</a> from
179 its nearest ancestor with an assigned level. The third argument of
180 type <code>List&lt;String></code> is optional and defaults to an
181 empty list if omitted. The appender names in the list are attached
182 to the designated logger. The fourth argument of type
183 <code>Boolean</code> is also optional and controls the <a
184 href="architecture.html#additivity">additivity flag</a>. If
185 omitted, it defaults to <code>null</code>.
186 </p>
187
188 <p>For example, the following script sets the level of the
189 "com.foo" logger to INFO.</p>
190
191 <pre class="prettyprint source">logger("com.foo", INFO)</pre>
192
193 <p>The next script sets the level of the "com.foo" logger to
194 DEBUG, and attaches the appender named "CONSOLE" to it.</p>
195
196 <pre class="prettyprint source">logger("com.foo", DEBUG, ["CONSOLE"])</pre>
197
198 <p>The next script is similar to the previous one, except that it
199 also sets the the additivity flag of the "com.foo" logger to
200 false.</p>
201
202 <pre class="prettyprint source">logger("com.foo", DEBUG, ["CONSOLE"], false)</pre>
203
204
205 <!-- ========================================================== -->
206 <h3>&#8226; <span class="code">appender(String name, Class clazz, Closure closure = null)</span></h3>
207
208 <p>The appender method takes the name of the appender being
209 configured as its first argument. The second mandatory argument is
210 the class of the appender to instantiate. The third argument is a
211 closure containing further configuration instructions. If omitted,
212 it defaults to null.</p>
213
214 <p>Most appenders require properties to be set and sub-components
215 to be injected to function properly. Properties are set using the
216 '=' operator (assignment). Sub-components are injected by invoking
217 a method named after the property and passing that method the
218 class to instantiate as an argument. This convention can be
219 applied recursively to configure properties as well as
220 sub-components of any appender sub-component. This approach is at
221 the heart of <em>logback.groovy</em> scripts and is probably the
222 only convention that needs learning.</p>
223
224 <p>For example, the following script instantiates a
225 <code>FileAppender</code> named "FILE", setting its <span
226 class="option">file</span> property to "testFile.log" and its
227 <span class="option">append</span> property to false. An encoder
228 of type <code>PatternLayoutEncoder</code> is injected into the
229 appender. The pattern property of the encoder is set to "%level
230 %logger - %msg%n". The appender is then attached to the root
231 logger.</p>
232
233 <pre class="prettyprint source">appender("FILE", FileAppender) {
234 file = "testFile.log"
235 append = true
236 encoder(PatternLayoutEncoder) {
237 pattern = "%level %logger - %msg%n"
238 }
239 }
240
241 root(DEBUG, ["FILE"])</pre>
242
243 <p>
244 </p>
245
246
247 <!-- ========================================================== -->
248 <h3>&#8226; <span class="code">timestamp(String datePattern, long timeReference = -1)</span></h3>
249
250 <p>The <code>timestamp()</code> method method returns a string
251 corresponding to the <code>timeReference</code> parameter
252 formatted according to the <code>datePattern</code> parameter. The
253 <code>datePattern</code> parameter should follow the conventions
254 defined by <a
255 href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>. If
256 the <code>timeReference</code> value is unspecified, it defaults
257 to -1, in which case current time, that is time when the
258 configuration file is parsed, is used as the time
259 reference. Depending on the circumstances, occasion, you might
260 wish to use <code>context.birthTime</code> as the time reference.
261 </p>
262
263 <p>In the next example, the <code>bySecond</code> variable is
264 assigned the current time in the "yyyyMMdd'T'HHmmss" format. The
265 "bySecond" variable is then used to define the value of the <span
266 class="option">file</span> property.
267 </p>
268
269 <pre class="prettyprint source"><b>def bySecond = timestamp("yyyyMMdd'T'HHmmss")</b>
270
271 appender("FILE", FileAppender) {
272 <b>file = "log-${bySecond}.txt"</b>
273 encoder(PatternLayoutEncoder) {
274 pattern = "%logger{35} - %msg%n"
275 }
276 }
277 root(DEBUG, ["FILE"])</pre>
278
279 <!-- ========================================================== -->
280 <h3>&#8226; <span class="code">conversionRule(String conversionWord, Class converterClass)</span></h3>
281
282 <p>After creating your own <a
283 href="layouts.html#customConversionSpecifier">conversion
284 specifier</a>, you need to inform logback of its existence. Here
285 is a sample logback.groovy file which instructs logback to use
286 MySampleConverter whenever the <code>%sample</code> conversion
287 word is encountered.
288 </p>
289
290 <pre class="prettyprint source">
291 import chapters.layouts.MySampleConverter
292
293 conversionRule("sample", MySampleConverter)
294 appender("STDOUT", ConsoleAppender) {
295 encoder(PatternLayoutEncoder) {
296 pattern = "%-4relative [%thread] %<b>sample</b> - %msg%n"
297 }
298 }
299 root(DEBUG, ["STDOUT"])</pre>
300
301 <!-- ========================================================== -->
302 <h3>&#8226; <span class="code">scan(String scanPeriod = null)</span></h3>
303
304 <p>Invoking the scan() method instructs logback to periodically
305 scan the logback.groovy file for changes. Whenever a change is
306 detected, the <em>logback.groovy</em> file is reloaded.</p>
307
308 <pre class="prettyprint source">scan()</pre>
309
310 <p>By default, the configuration file will be scanned for changes
311 once every minute. You can specify a different scanning period by
312 passing a "scanPeriod" string value. Values can be specified in
313 units of milliseconds, seconds, minutes or hours. Here is an
314 example:
315 </p>
316
317 <pre class="prettyprint source">scan("30 seconds")</pre>
318
319 <p>If no unit of time is specified, then the unit of time is
320 assumed to be milliseconds, which is usually inappropriate. If you
321 change the default scanning period, do not forget to specify a
322 time unit. For additional details on how scanning works, please
323 refer to the <a href="configuration.html#autoScan">section on
324 automatic reloading</a>.
325 </p>
326
327 <!-- ========================================================== -->
328
329 <h3>&#8226; <span class="code">statusListener(Class listenerClass)</span></h3>
330
331 <p>You can add a status listener by invoking the
332 <code>statusListener</code> method and passing a listener class as
333 an argument. Here is an example:</p>
334
335 <pre class="prettyprint source">import chapters.layouts.MySampleConverter
336
337 <b>// We highly recommended that you always add a status listener just</b>
338 <b>// after the last import statement and before all other statements</b>
339 <b>statusListener(OnConsoleStatusListener)</b></pre>
340
341 <p><a href="configuration.html#statusListener">Status listeners</a> were described in an earlier
342 chapter.</p>
343
344 <h3>&#8226; <span class="code">jmxConfigurator(String name)</span></h3>
345
346 <p>You can register a <a href="jmxConfig.html"><code>JMXConfigurator</code></a>
347 MBean with this method. Invoke it without any parameters to use Logback's
348 default ObjectName
349 (<code>ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator</code>)
350 for the registered MBean:</p>
351
352 <pre class="prettyprint source">jmxConfigurator()</pre>
353
354 <p>To change the value of the <code>Name</code> key to something other than "default",
355 simply pass in a different name as the parameter for the <code>jmxConfigurator</code>
356 method:</p>
357
358 <pre class="prettyprint source">jmxConfigurator('MyName')</pre>
359
360 <p>If you want define the ObjectName completely, use the same syntax but
361 pass in a valid ObjectName string representation as the parameter:</p>
362
363 <pre class="prettyprint source">jmxConfigurator('myApp:type=LoggerManager')</pre>
364
365 <p>The method will first attempt to use the parameter as an ObjectName,
366 and falls back to treating it as the value for the "Name" key if it doesn't
367 represent a valid ObjectName.</p>
368
369 <!-- ========================================================== -->
370
371 <h2 class="doAnchor" name="internalDSL">Internal DSL, i.e. it's
372 all groovy baby!</h2>
373
374 <p>The <em>logback.groovy</em> is an internal DSL meaning that its
375 contents are executed as a Groovy script. Thus, all the usual
376 Groovy constructs such as class imports, GString, variable
377 definitions, evaluation of $&#123;..&#125; expressions contained
378 within strings (GStrings), if-else statements are all available in
379 logback.groovy files. In the following discussion, we will present
380 typical uses of these Groovy constructs in <em>logback.groovy</em>
381 files.
382 </p>
383
384
385 <h3 class="doAnchor" name="varedef">Variable definitions and
386 GStrings</h3>
387
388 <p>You can define variables anywhere within a
389 <em>logback.groovy</em> file, then use the variable within a
390 GString. Here is an example.</p>
391
392 <pre class="prettyprint source">// define the USER_HOME variable setting its value
393 // to that of the "user.home" system property
394 <b>def USER_HOME = System.getProperty("user.home")</b>
395
396 appender("FILE", FileAppender) {
397 // make use of the USER_HOME variable
398 <b>file = "${USER_HOME}/myApp.log"</b>
399 encoder(PatternLayoutEncoder) {
400 pattern = "%msg%n"
401 }
402 }
403 root(DEBUG, ["FILE"])</pre>
404
405
406 <h3 class="doAnchor" name="printing">Printing on the console</h3>
407
408 <p>You can invoke Groovy's <code>println</code> method to print on
409 the console. Here is an example.</p>
410
411 <pre class="prettyprint source">def USER_HOME = System.getProperty("user.home");
412 <b>println "USER_HOME=${USER_HOME}"</b>
413
414 appender("FILE", FileAppender) {
415 <b>println "Setting [file] property to [${USER_HOME}/myApp.log]"</b>
416 file = "${USER_HOME}/myApp.log"
417 encoder(PatternLayoutEncoder) {
418 pattern = "%msg%n"
419 }
420 }
421 root(DEBUG, ["FILE"])</pre>
422
423
424 <h3 class="doAnchor" name="automaticallyExported">Automatically
425 exported fields</h3>
426
427 <h4 class="doAnchor" name="hostname">'hostname' variable</h4>
428
429 <p>The 'hostname' variable contains the name of the current
430 host. However, due to scoping rules that the authors cannot fully
431 explain, the 'hostname' variable is available only at the topmost
432 scope but not in nested scopes. The next example should get the
433 point across.
434 </p>
435
436 <pre class="prettyprint source">// will print "hostname is x" where x is the current host's name
437 println "Hostname is ${hostname}"
438
439 appender("STDOUT", ConsoleAppender) {
440 <b>// will print "hostname is null"</b>
441 <b>println "Hostname is ${hostname}" </b>
442 }</pre>
443
444 <p>If you wish to have the hostname variable be seen in all scopes,
445 you need to define another variable and assign it the value of
446 'hostname' as shown next.</p>
447
448 <pre class="prettyprint source">// define HOSTNAME by assigning it hostname
449 def HOSTNAME=hostname
450 // will print "hostname is x" where x is the current host's name
451 println "Hostname is ${HOSTNAME}"
452
453 appender("STDOUT", ConsoleAppender) {
454 // will print "hostname is x" where x is the current host's name
455 println "Hostname is ${HOSTNAME}"
456 }</pre>
457
458
459 <h3 class="doAnchor" name="everythingIsContext">Everything is
460 context aware with a reference to the current context</h3>
461
462 <p>The execution of the <em>logback.groovy</em> script is done
463 within the scope of a <a
464 href="../xref/ch/qos/logback/core/spi/ContextAware.html">ContextAware</a>
465 object. Thus, the current context is always accessible using the
466 '<code>context</code>' variable and you can invoke
467 <code>addInfo</code>(), <code>addWarn</code>() and
468 <code>addError</code>() methods to send status messages to the
469 context's <code>StatusManager</code>.</p>
470
471 <pre class="prettyprint source">// always a good idea to add an on console status listener
472 statusListener(OnConsoleStatusListener)
473
474 // set the context's name to wombat
475 <b>context.name = "wombat"</b>
476 // add a status message regarding context's name
477 <b>addInfo("Context name has been set to ${context.name}")</b>
478
479 def USER_HOME = System.getProperty("user.home");
480 // add a status message regarding USER_HOME
481 <b>addInfo("USER_HOME=${USER_HOME}")</b>
482
483 appender("FILE", FileAppender) {
484 // add a status message regarding the file property
485 <b>addInfo("Setting [file] property to [${USER_HOME}/myApp.log]")</b>
486 file = "${USER_HOME}/myApp.log"
487 encoder(PatternLayoutEncoder) {
488 pattern = "%msg%n"
489 }
490 }
491 root(DEBUG, ["FILE"])</pre>
492
493
494 <h3 class="doAnchor">Conditional configuration</h3>
495
496 <p>Given that Groovy is a fully-fledged programming language,
497 conditional statements allow for a single <em>logback.groovy</em>
498 file to adapt to various environments such as development, testing
499 or production.</p>
500
501 <p>In the next script, a console appender is activated on hosts
502 other than pixie or orion, our production machines. Note that the
503 output directory of the rolling file appender also depends on the
504 host.</p>
505
506 <pre class="prettyprint source">// always a good idea to add an on console status listener
507 statusListener(OnConsoleStatusListener)
508
509 def appenderList = ["ROLLING"]
510 def WEBAPP_DIR = "."
511 def consoleAppender = true;
512
513 // does hostname match pixie or orion?
514 if (hostname =~ /pixie|orion/) {
515 WEBAPP_DIR = "/opt/myapp"
516 consoleAppender = false
517 } else {
518 appenderList.add("CONSOLE")
519 }
520
521 if (consoleAppender) {
522 appender("CONSOLE", ConsoleAppender) {
523 encoder(PatternLayoutEncoder) {
524 pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
525 }
526 }
527 }
528
529 appender("ROLLING", RollingFileAppender) {
530 encoder(PatternLayoutEncoder) {
531 Pattern = "%d %level %thread %mdc %logger - %m%n"
532 }
533 rollingPolicy(TimeBasedRollingPolicy) {
534 FileNamePattern = "${WEBAPP_DIR}/log/translator-%d{yyyy-MM}.zip"
535 }
536 }
537
538 root(INFO, appenderList)</pre>
539
540
541
542
543 <script src="../templates/footer.js" type="text/javascript"></script>
544
545 </div>
546 </body>
547 </html>