/usr/share/doc/liblogback-java/manual/configuration.html is in liblogback-java-doc 1:1.1.3-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Chapter 3: Configuration</title>
<link rel="stylesheet" type="text/css" href="../css/common.css" />
<link rel="stylesheet" type="text/css" href="../css/screen.css" media="screen" />
<link rel="stylesheet" type="text/css" href="../css/_print.css" media="print" />
<link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen" />
</head>
<body onload="prettyPrint(); decorate();">
<script type="text/javascript">prefix='../'</script>
<script type="text/javascript" src="../js/prettify.js"></script>
<script src="../templates/header.js" type="text/javascript"></script>
<script type="text/javascript" src="../js/dsl.js"></script>
<script type="text/javascript" src="../js/jquery-min.js"></script>
<script type="text/javascript" src="../js/decorator.js"></script>
<div id="left">
<noscript>Please turn on Javascript to view this menu</noscript>
<script src="../templates/left.js" type="text/javascript"></script>
</div>
<div id="right">
<script src="menu.js" type="text/javascript"></script>
</div>
<div id="content" class="chapter">
<h1>Chapter 3: Logback configuration</h1>
<div class="quote">
<p><em>In symbols one observes an advantage in discovery which
is greatest when they express the exact nature of a thing
briefly and, as it were, picture it; then indeed the labor of
thought is wonderfully diminished.</em>
</p>
<p>—GOTTFRIED WILHELM LEIBNIZ</p>
</div>
<script src="../templates/creative.js" type="text/javascript"></script>
<p>We start by presenting ways for configuring logback, with many
example configuration scripts. Joran, the configuration framework
upon which logback relies will be presented in <a
href="onJoran.html">a later chapter</a>.
</p>
<h2 class="doAnchor" name="auto_configuration">Configuration in
logback</h2>
<p>Inserting log requests into the application code requires a
fair amount of planning and effort. Observation shows that
approximately four percent of code is dedicated to
logging. Consequently, even a moderately sized application will
contain thousands of logging statements embedded within its
code. Given their number, we need tools to manage these log
statements.
</p>
<p>Logback can be configured either programmatically or with a
configuration script expressed in XML or Groovy format. By the
way, existing log4j users can convert their
<em>log4j.properties</em> files to <em>logback.xml</em> using our
<a
href="http://logback.qos.ch/translator/">PropertiesTranslator</a>
web-application.
</p>
<p>Let us begin by discussing the initialization steps that
logback follows to try to configure itself:
</p>
<ol>
<li>
<p>Logback tries to find a file called
<em>logback.groovy</em> <a
href="../faq.html#configFileLocation">in the
classpath</a>.</p>
</li>
<li>
<p>If no such file is found, logback tries to find a file
called <em>logback-test.xml</em> <a
href="../faq.html#configFileLocation">in the
classpath</a>.</p>
</li>
<li><p>If no such file is found, it checks for the file
<em>logback.xml</em> <a
href="../faq.html#configFileLocation">in the
classpath</a>..</p>
</li>
<li><p>If no such file is found, and the executing JVM has the
<a href="http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html">
ServiceLoader</a> (JDK 6 and above) the ServiceLoader will be used to resolve an
implementation of <a href="../xref/ch/qos/logback/classic/spi/Configurator.html">
<code>com.qos.logback.classic.spi.Configurator</code></a>.
The first implementation found will be used.
See <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html">
ServiceLoader documentation for more details</a>.
</li>
<li><p>If none of the above succeeds, logback configures itself
automatically using the <a
href="../xref/ch/qos/logback/classic/BasicConfigurator.html"><code>BasicConfigurator</code></a>
which will cause logging output to be directed to the console.
</p>
</li>
</ol>
<p>The fourth and last step is meant to provide a default (but
very basic) logging functionality in the absence of a
configuration file.
</p>
<p>If you are using Maven and if you place the
<em>logback-test.xml</em> under the
<em>src/test/resources</em> folder, Maven will ensure that it
won't be included in the artifact produced. Thus, you can use a
different configuration file, namely <em>logback-test.xml</em>
during testing, and another file, namely, <em>logback.xml</em>, in
production. The same principle applies by analogy for Ant.
</p>
<h3 class="doAnchor" name="automaticConf">Automatically
configuring logback</h3>
<p>The simplest way to configure logback is by letting logback
fall back to its default configuration. Let us give a taste of how
this is done in an imaginary application called
<code>MyApp1</code>.
</p>
<p class="example">Example: Simple example of
<code>BasicConfigurator</code> usage <a
href="../xref/chapters/configuration/MyApp1.html">(logback-examples/src/main/java/chapters/configuration/MyApp1.java)</a></p>
<pre class="prettyprint source">package manual.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyApp1 {
final static Logger logger = LoggerFactory.getLogger(MyApp1.class);
public static void main(String[] args) {
logger.info("Entering application.");
Foo foo = new Foo();
foo.doIt();
logger.info("Exiting application.");
}
}</pre>
<p>This class defines a static logger variable. It then instantiates
a <code>Foo</code> object. The <code>Foo</code> class is listed
below:
</p>
<p class="example">Example: Small class doing logging
<a href="../xref/chapters/configuration/Foo.html">(logback-examples/src/main/java/chapters/configuration/Foo.java)</a>
</p>
<pre class="prettyprint source">package chapters.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
static final Logger logger = LoggerFactory.getLogger(Foo.class);
public void doIt() {
logger.debug("Did it again!");
}
}</pre>
<p>In order to run the examples in this chapter, you need to make
sure that certain jar files are present on the class path. Please
refer to the <a href="../setup.html">setup page</a> for further
details.
</p>
<p>Assuming the configuration files <em>logback-test.xml</em> or
<em>logback.xml</em> are not present, logback will default to
invoking <a
href="../xref/ch/qos/logback/classic/BasicConfigurator.html"><code>BasicConfigurator</code></a>
which will set up a minimal configuration. This minimal
configuration consists of a <code>ConsoleAppender</code> attached
to the root logger. The output is formatted using a
<code>PatternLayoutEncoder</code> set to the pattern
<em>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</em>. Moreover,
by default the root logger is assigned the <code>DEBUG</code>
level.
</p>
<p>Thus, the output of the command <em>java chapters.configuration.MyApp1</em>
should be similar to:
</p>
<p class="source">16:06:09.031 [main] INFO chapters.configuration.MyApp1 - Entering application.
16:06:09.046 [main] DEBUG chapters.configuration.Foo - Did it again!
16:06:09.046 [main] INFO chapters.configuration.MyApp1 - Exiting application.</p>
<p class="highlight">Except code that configures logback (if such
code exists) client code does not need to depend on
logback. Applications that use logback as their logging framework
will have a compile-time dependency on SLF4J but not logback.
</p>
<p>The <code>MyApp1</code> application links to logback via calls
to <code>org.slf4j.LoggerFactory</code> and
<code>org.slf4j.Logger</code> classes, retrieve the loggers it
wishes to use, and chugs on. Note that the only dependencies of
the <code>Foo</code> class on logback are through
<code>org.slf4j.LoggerFactory</code> and
<code>org.slf4j.Logger</code> imports. Except code that configures
logback (if such code exists) client code does not need to depend
on logback. Since SLF4J permits the use of any logging
framework under its abstraction layer, it is easy to migrate
large bodies of code from one logging framework to another.
</p>
<h3>Automatic configuration with <em>logback-test.xml</em> or
<em>logback.xml</em></h3>
<p>As mentioned earlier, logback will try to configure itself using
the files <em>logback-test.xml</em> or <em>logback.xml</em> if
found on the class path. Here is a configuration file equivalent to
the one established by <code>BasicConfigurator</code> we've just
seen.
</p>
<p class="example">Example: Basic configuration file
(logback-examples/src/main/java/chapters/configuration/sample0.xml)</p>
<span class="asGroovy" onclick="return asGroovy('sample0');">View as .groovy</span>
<pre id="sample0" class="prettyprint source"><configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>After you have renamed <em>sample0.xml</em> as
<em>logback.xml</em> (or <em>logback-test.xml</em>) place it into a
directory accessible from the class path. Running the <em>MyApp1</em>
application should give identical results to its previous run.</p>
<h4 class="doAnchor" name="automaticStatusPrinting">Automatic
printing of status messages in case of warning or errors</h4>
<p class="highlight">If warning or errors occur during the parsing
of the configuration file, logback will automatically print its
internal status messages on the console.</p>
<p>If warnings or errors occur during the parsing of the
configuration file, logback will automatically print its internal
status data on the console. Note that to avoid duplication,
automatic status printing is disabled if the user explicitly
registers a status listener (defined below).</p>
<p>In the absence of warnings or errors, if you still wish to
inspect logback's internal status, then you can instruct logback to
print status data by invoking the <code>print()</code> of the
<code>StatusPrinter</code> class. The <em>MyApp2</em> application
shown below is identical to <em>MyApp1</em> except for the addition
of two lines of code for printing internal status data.</p>
<p class="example">Example: Print logback's internal status
information <a
href="../xref/chapters/configuration/MyApp2.html">(logback-examples/src/main/java/chapters/configuration/MyApp2.java)</a></p>
<pre class="prettyprint lang-java source">
public static void main(String[] args) {
// assume SLF4J is bound to logback in the current environment
<b>LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();</b>
// print logback's internal status
<b>StatusPrinter.print(lc);</b>
...
}</pre>
<p>If everything goes well, you should see the following output on the console</p>
<div class="source longline"><pre>17:44:58,578 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback-test.xml]
17:44:58,671 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
17:44:58,671 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
17:44:58,687 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
17:44:58,812 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Popping appender named [STDOUT] from the object stack
17:44:58,812 |-INFO in ch.qos.logback.classic.joran.action.LevelAction - root level set to DEBUG
17:44:58,812 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[root]
17:44:58.828 [main] INFO chapters.configuration.MyApp2 - Entering application.
17:44:58.828 [main] DEBUG chapters.configuration.Foo - Did it again!
17:44:58.828 [main] INFO chapters.configuration.MyApp2 - Exiting application.
</pre></div>
<p>At the end of this output, you can recognize the lines that were
printed in the previous example. You should also notice the
logback's internal messages, a.k.a. <code>Status</code> objects,
which allow convenient access to logback's internal state.
</p>
<p>Instead of invoking <code>StatusPrinter</code> programmatically
from your code, you can instruct the configuration file to dump
status data, even in the absence of errors. To achieve this, you
need to set the <span class="attr">debug</span> attribute of the
<em>configuration</em> element, i.e. the top-most element in the
configuration file, as shown below. Please note that this <span
class="attr">debug</span> attribute relates only to the status
data. It does <em>not</em> affect logback's configuration
otherwise, in particular with respect to logger levels. (If you are
asking, no, the root logger will <em>not</em> be set to
<code>DEBUG</code>.)
</p>
<p class="example">Example: Basic configuration file using debug
mode
(logback-examples/src/main/java/chapters/configuration/sample1.xml)</p>
<span class="asGroovy" onclick="return asGroovy('sample1');">View as .groovy</span>
<pre id="sample1" class="prettyprint source">
<configuration <span class="big bold">debug="true"</span>>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are by default assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>Setting the <code>debug</code> attribute within the
<configuration> element will output status information,
assuming that:
</p>
<ol>
<li>the configuration file is found</li>
<li>the configuration file is well-formed XML.</li>
</ol>
<p>If any of these two conditions is not fulfilled, Joran cannot
interpret the <span class="attr">debug</span> attribute since the
configuration file cannot be read. If the configuration file is
found but is malformed, then logback will detect the error
condition and automatically print its internal status on the
console. However, if the configuration file cannot be found,
logback will not automatically print its status data, since this is
not necessarily an error condition. Programmatically invoking
<code>StatusPrinter.print()</code> as shown in the <a
href="../xref/chapters/configuration/MyApp2.html"><em>MyApp2</em></a>
application above ensures that status information is printed in
every case.</p>
<p><span class="label">Forcing status output</span> In the absence
of status messages, tracking down a rogue <em>logback.xml</em>
configuration file can be difficult, especially in production where
the application source cannot be easily modified. To help identify
the location of a rogue configuration file, you can set a
<code>StatusListener</code> via the "logback.statusListenerClass"
system property (<a href="#logback.statusLC">defined below</a>) to
force output of status messages. The "logback.statusListenerClass"
system property can also be used to silence output automatically
generated in case of errors.
</p>
<h3 class="doAnchor" name="configFileProperty">Specifying the
location of the default configuration file as a system
property</h3>
<p>You may specify the location of the default configuration file
with a system property named
<code>"logback.configurationFile"</code>. The value of this
property can be a URL, a resource on the class path or a path to a
file external to the application.
</p>
<p class="source">java <b>-Dlogback.configurationFile=/path/to/config.xml</b> chapters.configuration.MyApp1</p>
<p>Note that the file extension must be ".xml" or ".groovy". Other
extensions are ignored. <a href="#logback.statusLC">Explicitly
registering a status listener</a> may help debugging issues
locating the configuration file.</p>
<h3 class="doAnchor" name="autoScan">Automatically reloading
configuration file upon modification</h3>
<p class="highlight">Logback-classic can scan for changes in its
configuration file and automatically reconfigure itself when the
configuration file changes.</p>
<p>If instructed to do so, logback-classic will scan for changes in
its configuration file and automatically reconfigure itself when
the configuration file changes. In order to instruct
logback-classic to scan for changes in its configuration file and
to automatically re-configure itself set the <span
class="attr">scan</span> attribute of the
<code><configuration></code> element to true, as shown next.
</p>
<p class="example">Example: Scanning for changes in configuration
file and automatic re-configuration
(logback-examples/src/main/java/chapters/configuration/scan1.xml)</p>
<span class="asGroovy" onclick="return asGroovy('scan1');">View as .groovy</span>
<pre id="scan1" class="prettyprint source">
<configuration <b>scan="true"</b>>
...
</configuration> </pre>
<p>By default, the configuration file will be scanned for changes
once every minute. You can specify a different scanning period by
setting the <span class="attr">scanPeriod</span> attribute of the
<code><configuration></code> element. Values can be specified in
units of milliseconds, seconds, minutes or hours. Here is an
example:</p>
<p class="example">Example: Specifying a different scanning period
(logback-examples/src/main/java/chapters/configuration/scan2.xml)</p>
<span class="asGroovy" onclick="return asGroovy('scan2');">View as .groovy</span>
<pre id="scan2" class="prettyprint source">
<configuration scan="true" <b>scanPeriod="30 seconds"</b> >
...
</configuration> </pre>
<p><span class="label">Note</span> If no unit of time is specified,
then the unit of time is assumed to be milliseconds, which is
usually inappropriate. If you change the default scanning period,
do not forget to specify a time unit.
</p>
<p>Behind the scenes, when you set the scan attribute to true, a
<code>TurboFilter</code> called <a
href="../xref/ch/qos/logback/classic/turbo/ReconfigureOnChangeFilter.html">ReconfigureOnChangeFilter</a>
will be installed. TurboFilters are described in a <a
href="filters.html#TurboFilter">later chapter</a>. As a
consequence, scanning is done "in-thread", that is any time a
printing method of logger is invoked. For example, for a logger
named <code>myLogger</code>, when you write
"myLogger.debug("hello");", and if the scan attribute is set to
true, then <code>ReconfigureOnChangeFilter</code> will be
invoked. Moreover, the said filter will be invoked even if
<code>myLogger</code> is disabled for the DEBUG level.
</p>
<p class="highlight">When a configuration file changes, it will be
automatically reloaded but only after several logger invocations
and after a delay determined by the scanning period.
</p>
<p>Given that <code>ReconfigureOnChangeFilter</code> is invoked
every time <em>any</em> logger is invoked, regardless of logger
level, <code>ReconfigureOnChangeFilter</code> is absolutely
performance critical. So much so that in fact, the check whether
the scan period has elapsed or not, is too costly in itself. In
order to improve performance,
<code>ReconfigureOnChangeFilter</code> is in reality "alive" only
once every <em>N</em> logging operations. Depending on how often
your application logs, the value of <em>N</em> can be modified on
the fly by logback. By default N is 16, although it can go as high
as 2^16 (= 65536) for CPU-intensive applications.
</p>
<p>In short, when a configuration file changes, it will be
automatically reloaded but only after several logger invocations
<em>and</em> after a delay determined by the scanning period.
</p>
<h3 class="doAnchor" name="joranDirectly">Invoking
<code>JoranConfigurator</code> directly</h3>
<p>Logback relies on a configuration library called Joran, part of
logback-core. Logback's default configuration mechanism invokes
<code>JoranConfigurator</code> on the default configuration file it
finds on the class path. If you wish to override logback's default
configuration mechanism for whatever reason, you can do so by
invoking <code>JoranConfigurator</code> directly. The next
application, <em>MyApp3</em>, invokes JoranConfigurator on a
configuration file passed as a parameter.</p>
<p class="example">Example: Invoking <code>JoranConfigurator</code>
directly <a
href="../xref/chapters/configuration/MyApp3.html">(logback-examples/src/main/java/chapters/configuration/MyApp3.java)</a></p>
<pre class="prettyprint source">package chapters.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
public class MyApp3 {
final static Logger logger = LoggerFactory.getLogger(MyApp3.class);
public static void main(String[] args) {
// assume SLF4J is bound to logback in the current environment
<b>LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();</b>
<b>try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
context.reset();
configurator.doConfigure(args[0]);
} catch (JoranException je) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);</b>
logger.info("Entering application.");
Foo foo = new Foo();
foo.doIt();
logger.info("Exiting application.");
}
}</pre>
<p>This application fetches the <code>LoggerContext</code>
currently in effect, creates a new <code>JoranConfigurator</code>,
sets the context on which it will operate, resets the logger
context, and then finally asks the configurator to configure the
context using the configuration file passed as a parameter to the
application. Internal status data is printed in case of warnings or
errors. Note that for multi-step configuration,
<code>context.reset()</code> invocation should be omitted.</p>
<h3 class="doAnchor" name="viewingStatusMessages">Viewing status
messages </h3>
<p>Logback collects its internal status data in a <code><a
href="../xref/ch/qos/logback/core/status/StatusManager.html">StatusManager</a></code>
object, accessible via the <code>LoggerContext</code>.
</p>
<p>Given a <code>StatusManager</code> you can access all the status
data associated with a logback context. To keep memory usage at
reasonable levels, the default <code>StatusManager</code>
implementation stores the status messages in two separate parts:
the header part and the tail part. The header part stores the first
<em>H</em> status messages whereas the tail part stores the last
<em>T</em> messages. At present time <em>H</em>=<em>T</em>=150,
although these values may change in future releases.</p>
<p>Logback-classic ships with a servlet called
ViewStatusMessagesServlet. This servlet prints the contents of the
<code>StatusManager</code> associated with the current
<code>LoggerContext</code> as an HTML table. Here is sample output.
</p>
<a href="images/chapters/configuration/lbClassicStatus.jpg">
<img src="images/chapters/configuration/lbClassicStatus.jpg" alt="click to enlarge" width="90%"/>
</a>
<p>To add this servlet to your web-application, add the following
lines to its <em>WEB-INF/web.xml</em> file.</p>
<pre class="prettyprint source"> <servlet>
<servlet-name>ViewStatusMessages</servlet-name>
<servlet-class>ch.qos.logback.classic.ViewStatusMessagesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewStatusMessages</servlet-name>
<url-pattern>/lbClassicStatus</url-pattern>
</servlet-mapping></pre>
<p>The <code>ViewStatusMessages</code> servlet will be viewable at
the URL <code>http://host/yourWebapp/lbClassicStatus</code>
</p>
<h3 class="doAnchor" name="statusListener">Listening to status
messages</h3>
<p>You may also attach a <code>StatusListener</code> to a
<code>StatusManager</code> so that you can take immediate action in
response to status messages, especially to messages occurring after
logback configuration. Registering a status listener is a
convenient way to supervise logback's internal state without human
intervention.
</p>
<p>Logback ships with a <code>StatusListener</code> implementation
called <code><a
href="../xref/ch/qos/logback/core/status/OnConsoleStatusListener.html">OnConsoleStatusListener</a></code>
which, as its name indicates, prints all <em>new</em> incoming
status messages on the console.
</p>
<p>Here is <a
href="../xref/chapters/configuration/AddStatusListenerApp.html">sample
code</a> to register an <code>OnConsoleStatusListener</code>
instance with the StatusManager.
</p>
<pre class="prettyprint source"> LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
StatusManager statusManager = lc.getStatusManager();
OnConsoleStatusListener onConsoleListener = new OnConsoleStatusListener();
statusManager.add(onConsoleListener);</pre>
<p>Note that the registered status listener will only receive status
events subsequent to its registration. It will not receive prior
messages. Thus, it is usually a good idea to place status listener
registration directives at top of the configuration file before
other directives.</p>
<p>It is also possible to register one or more status listeners
within a configuration file. Here is an example.</p>
<p class="example">Example: Registering a status listener
(logback-examples/src/main/java/chapters/configuration/onConsoleStatusListener.xml)</p>
<span class="asGroovy" onclick="return asGroovy('onConsoleStatusListener');">View as .groovy</span>
<pre id="onConsoleStatusListener" class="prettyprint source"><configuration>
<b><statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /></b>
... the rest of the configuration file
</configuration></pre>
<h3 class="doAnchor"
name="logback.statusLC">"logback.statusListenerClass" system
property</h3>
<p>One may also register a status listener by setting the
"logback.statusListenerClass" Java system property to the name of
the listener class you wish to register. For example,
</p>
<p class="source">java <b>-Dlogback.statusListenerClass</b>=ch.qos.logback.core.status.OnConsoleStatusListener ...</p>
<p>Logback ships with several status listener implementations. <a
href="../xref/ch/qos/logback/core/status/OnConsoleStatusListener.html">OnConsoleStatusListener</a>
prints incoming status messages on the console, i.e. on
System.out. <a
href="../xref/ch/qos/logback/core/status/OnErrorConsoleStatusListener.html">OnErrorConsoleStatusListener</a>
prints incoming status messages on System.err. <a
href="../xref/ch/qos/logback/core/status/NopStatusListener.html">NopStatusListener</a>
drops incoming status messages.</p>
<p>Note that <a href="#automaticStatusPrinting">automatic status
printing</a> (in case of errors) is disabled if any status listener
is registered during configuration and in particular if the user
specifies a status listener via the "logback.statusListenerClass"
system. Thus, by setting <code>NopStatusListener</code> as a status
listener, you can silence internal status printing altogether. </p>
<p class="source">java <b>-Dlogback.statusListenerClass</b>=ch.qos.logback.core.status.NopStatusListener ...</p>
<h3 class="doAnchor" name="stopContext">Stopping
logback-classic</h3>
<p>In order to release the resources used by logback-classic, it is
always a good idea to stop the logback context. Stopping the
context will close all appenders attached to loggers defined by the
context and stop any active threads.
</p>
<pre class="prettyprint lang-java source">
import org.sflf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
...
// assume SLF4J is bound to logback-classic in the current environment
<b>LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();</b>
<b>loggerContext.stop();</b></pre>
<p>In web-applications the above code could be invoked from within
the <a
href="http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html#contextDestroyed(javax.servlet.ServletContextEvent)">contextDestroyed</a>
method of <code>ServletContextListener</code> in order to stop
logback-classic and release resources.
</p>
<h4 class="doAnchor" name="shutdownHook">Stopping logback-classic
via a shutdown hook</h4>
<p>Installing a JVM shutdown hook is a convenient way for shutting
down logback and releasing associated resources.
</p>
<pre class="prettyprint source"><configuration debug="true">
<!-- in the absence of the class attribute, assume
ch.qos.logback.core.hook.DelayingShutdownHook -->
<b><shutdownHook/></b>
....
</configuration></pre>
<p>The default shutdown hook, namely <a
href="../apidocs/ch/qos/logback/core/hook/DelayingShutdownHook.html">DelayingShutdownHook</a>,
can delay shutdown by a user specified duration. Note that you may
install a shutdown hook of your own making by setting the <span
class="attr">class</span> attribute to correspond to your shutdown
hook's class name.</p>.
<h2 class="doAnchor" name="syntax">Configuration file syntax</h2>
<p>As you have seen thus far in the manual with plenty of examples
still to follow, logback allows you to redefine logging behavior
without needing to recompile your code. Indeed, you can easily
configure logback so as to disable logging for certain parts of
your application, or direct output to a UNIX Syslog daemon, to a
database, to a log visualizer, or forward logging events to a
remote logback server, which would log according to local server
policy, for example by forwarding the log event to a second logback
server.
</p>
<p>The remainder of this section presents the syntax of
configuration files.
</p>
<p>As will be demonstrated over and over, the syntax of logback
configuration files is extremely flexible. As such, it is not
possible to specify the allowed syntax with a DTD file or an XML
schema. Nevertheless, the very basic structure of the configuration
file can be described as, <code><configuration></code> element,
containing zero or more <code><appender></code> elements,
followed by zero or more <code><logger></code> elements,
followed by at most one <code><root></code> element. The
following diagram illustrates this basic structure.</p>
<p align="left">
<img src="images/chapters/configuration/basicSyntax.png"
alt="basic Syntax" title="Basic configuration file structure"/>
</p>
<p class="highlight">If you are unsure which case to use for a
given tag name, just follow the <a
href="http://en.wikipedia.org/wiki/CamelCase">camelCase
convention</a> which is almost always the correct convention.</p>
<h4 class="doAnchor" name="caseSensitivity">Case sensitivity of
tag names</h4>
<p>Since logback version 0.9.17, tag names pertaining to explicit
rules are case insensitive. For example, <code><logger></code>, <code><Logger></code> and
<code><LOGGER></code> are valid configuration elements and will
be interpreted in the same way. Note that XML well-formedness
rules still apply, if you open a tag as <code><xyz></code> you
must close it as <code></xyz></code>, <code></XyZ></code>
will not work. As for <a href="onJoran.html#implicit">implicit
rules</a>, tag names are case sensitive except for the first
letter. Thus, <code><xyz></code> and <code><Xyz></code> are
equivalent but not <code><xYz></code>. Implicit rules usually
follow the <a href="http://en.wikipedia.org/wiki/CamelCase">camelCase</a>
convention, common in the Java world. Since it is not
easy to tell when a tag is associated with an explicit action and
when it is associated with an implicit action, it is not trivial
to say whether an XML tag is case-sensitive or insensitive with
respect to the first letter. If you are unsure which case to use
for a given tag name, just follow the camelCase convention which
is almost always the correct convention.
</p>
<h4 class="doAnchor" name="loggerElement">Configuring loggers, or
the <code><logger></code> element</h4>
<p>At this point you should have at least some understanding of <a
href="architecture.html#effectiveLevel">level inheritance</a> and
the <a href="architecture.html#basic_selection">basic selection
rule</a>. Otherwise, and unless you are an Egyptologist, logback
configuration will be no more meaningful to you than are
hieroglyphics.
</p>
<p>A logger is configured using the <code><logger></code>
element. A <code><logger></code> element takes exactly one
mandatory <span class="attr">name</span> attribute, an optional
<span class="attr">level</span> attribute, and an optional <span
class="attr">additivity</span> attribute, admitting the values
<em>true</em> or <em>false</em>. The value of the <span
class="attr">level</span> attribute admitting one of the
case-insensitive string values TRACE, DEBUG, INFO, WARN, ERROR,
ALL or OFF. The special case-insensitive value <em>INHERITED</em>,
or its synonym <em>NULL</em>, will force the level of the logger
to be inherited from higher up in the hierarchy. This comes in
handy if you set the level of a logger and later decide that
it should inherit its level.
</p>
<p class="highlight"> Note that unlike log4j, logback-classic does
<em>not</em> close nor remove any previously referenced appenders
when configuring a given logger.
</p>
<p>The <code><logger></code> element may contain zero or more
<code><appender-ref></code> elements; each appender thus
referenced is added to the named logger. Note that unlike log4j,
logback-classic does <em>not</em> close nor remove any previously
referenced appenders when configuring a given logger.
</p>
<h4 class="doAnchor" name="rootElement">Configuring the root
logger, or the <code><root></code> element</h4>
<p>The <code><root></code> element configures the root
logger. It supports a single attribute, namely the <span
class="attr">level</span> attribute. It does not allow any other
attributes because the additivity flag does not apply to the root
logger. Moreover, since the root logger is already named as
"ROOT", it does not allow a name attribute either. The value of the
level attribute can be one of the case-insensitive strings TRACE,
DEBUG, INFO, WARN, ERROR, ALL or OFF. Note that the level of the
root logger cannot be set to INHERITED or NULL.
</p>
<p class="highlight">Note that unlike log4j, logback-classic does
<em>not</em> close nor remove any previously referenced appenders
when configuring the root logger.</p>
<p> Similarly to the <code><logger></code> element, the
<code><root></code> element may contain zero or more
<code><appender-ref></code> elements; each appender thus
referenced is added to the root logger. Note that unlike log4j,
logback-classic does <em>not</em> close nor remove any previously
referenced appenders when configuring the root logger. </p>
<h4>Example</h4>
<p>Setting the level of a logger or root logger is as simple as
declaring it and setting its level, as the next example
illustrates. Suppose we are no longer interested in seeing any
DEBUG messages from any component belonging to the
"chapters.configuration" package. The following configuration file
shows how to achieve that.
</p>
<p class="example">Example: Setting the level of a logger
(logback-examples/src/main/java/chapters/configuration/sample2.xml)</p>
<span class="asGroovy" onclick="return asGroovy('sample2');">View as .groovy</span>
<pre id="sample2" class="prettyprint source"><configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<b><logger name="chapters.configuration" level="INFO"/></b>
<!-- Strictly speaking, the level attribute is not necessary since -->
<!-- the level of the root level is set to DEBUG by default. -->
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>When the above configuration file is given as argument to the
<em>MyApp3</em> application, it will yield the following output:
</p>
<pre class="source">17:34:07.578 [main] INFO chapters.configuration.MyApp3 - Entering application.
17:34:07.578 [main] INFO chapters.configuration.MyApp3 - Exiting application.</pre>
<p>Note that the message of level DEBUG generated by the <a
href="../xref/chapters/configuration/Foo.html">"chapters.configuration.Foo"</a>
logger has been suppressed. See also the Foo class.</p>
<p>You can configure the levels of as many loggers as you wish. In
the next configuration file, we set the level of the
<em>chapters.configuration</em> logger to INFO but at the same time set the level
of the <em>chapters.configuration.Foo</em> logger to <code>DEBUG</code>.
</p>
<p class="example">Example: Setting the level of multiple loggers
(logback-examples/src/main/java/chapters/configuration/sample3.xml)</p>
<span class="asGroovy" onclick="return asGroovy('sample3');">View as .groovy</span>
<pre id="sample3" class="source prettyprint"><configuration>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<b><logger name="chapters.configuration" level="INFO" /></b>
<b><logger name="chapters.configuration.Foo" level="DEBUG" /></b>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>Running <code>MyApp3</code> with this configuration file will
result in the following output on the console:
</p>
<p class="prettyprint source">17:39:27.593 [main] INFO chapters.configuration.MyApp3 - Entering application.
17:39:27.593 [main] DEBUG chapters.configuration.Foo - Did it again!
17:39:27.593 [main] INFO chapters.configuration.MyApp3 - Exiting application.</p>
<p>The table below list the loggers and their levels, after
<code>JoranConfigurator</code> has configured logback with the
<em>sample3.xml</em> configuration file.
</p>
<table class="bodyTable">
<tr>
<th>Logger name</th>
<th>Assigned Level</th>
<th>Effective Level</th>
</tr>
<tr>
<td>root</td>
<td><code>DEBUG</code></td>
<td><code>DEBUG</code></td>
</tr>
<tr class="alt">
<td>chapters.configuration</td>
<td><code>INFO</code></td>
<td><code>INFO</code></td>
</tr>
<tr>
<td>chapters.configuration.MyApp3</td>
<td><code>null</code></td>
<td><code>INFO</code></td>
</tr>
<tr class="alt">
<td>chapters.configuration.Foo</td>
<td><code>DEBUG</code></td>
<td><code>DEBUG</code></td>
</tr>
</table>
<p>It follows that the two logging statements of level
<code>INFO</code> in the <code>MyApp3</code> class as well as the
DEBUG messages in <code>Foo.doIt()</code> are all enabled. Note that
the level of the root logger is always set to a non-null value,
DEBUG by default.
</p>
<p>Let us note that the <a
href="architecture.html#basic_selection">basic-selection rule</a>
depends on the effective level of the logger being invoked, not the
level of the logger where appenders are attached. Logback will first
determine whether a logging statement is enabled or not, and if
enabled, it will invoke the appenders found in the logger hierarchy,
regardless of their level. The configuration file
<em>sample4.xml</em> is a case in point:
</p>
<p class="example">Example: Logger level sample
(logback-examples/src/main/java/chapters/configuration/sample4.xml)</p>
<span class="asGroovy" onclick="return asGroovy('sample4');">View as .groovy</span>
<pre id="sample4" class="prettyprint source"><configuration>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<b><logger name="chapters.configuration" level="INFO" /></b>
<!-- turn OFF all logging (children can override) -->
<root <b>level="OFF"</b>>
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>The following table lists the loggers and their levels after
applying the <em>sample4.xml</em> configuration file.
</p>
<table class="bodyTable">
<tr>
<th>Logger name</th>
<th>Assigned Level</th>
<th>Effective Level</th>
</tr>
<tr>
<td>root</td>
<td><code>OFF</code></td>
<td><code>OFF</code></td>
</tr>
<tr class="alt">
<td>chapters.configuration</td>
<td><code>INFO</code></td>
<td><code>INFO</code></td>
</tr>
<tr>
<td>chapters.configuration.MyApp3</td>
<td><code>null</code></td>
<td><code>INFO</code></td>
</tr>
<tr class="alt">
<td>chapters.configuration.Foo</td>
<td><code>null</code></td>
<td><code>INFO</code></td>
</tr>
</table>
<p>The ConsoleAppender named <em>STDOUT</em>, the only configured
appender in <em>sample4.xml</em>, is attached to the root logger
whose level is set to <code>OFF</code>. However, running
<em>MyApp3</em> with configuration script <em>sample4.xml</em> will
yield:
</p>
<div class="source"><pre>17:52:23.609 [main] INFO chapters.configuration.MyApp3 - Entering application.
17:52:23.609 [main] INFO chapters.configuration.MyApp3 - Exiting application.</pre></div>
<p>Thus, the level of the root logger has no apparent effect because
the loggers in <code>chapters.configuration.MyApp3</code> and
<code>chapters.configuration.Foo</code> classes are all enabled for the
<code>INFO</code> level. As a side note, the <em>chapters.configuration</em>
logger exists by virtue of its declaration in the configuration file
- even if the Java source code does not directly refer to it.
</p>
<h4 class="doAnchor" name="configuringAppenders">Configuring
Appenders</h4>
<p>An appender is configured with the <code><appender></code>
element, which takes two mandatory attributes <span
class="attr">name</span> and <span class="attr">class</span>. The
<span class="attr">name</span> attribute specifies the name of the
appender whereas the <span class="attr">class</span> attribute
specifies the fully qualified name of the appender class to
instantiate. The <code><appender></code> element may contain zero
or one <code><layout></code> elements, zero or more
<code><encoder></code> elements and zero or more
<code><filter></code> elements. Apart from these three common
elements, <code><appender></code> elements may contain any number
of elements corresponding to JavaBean properties of the appender
class. Seamlessly supporting any property of a given logback
component is one of the major strengths of <a
href="onJoran.html">Joran</a> as discussed in a later chapter. The
following diagram illustrates the common structure. Note that
support for properties is not visible.
</p>
<p align="left">
<img src="images/chapters/configuration/appenderSyntax.png"
alt="Appender Syntax" title="Appender element syntax"/>
</p>
<p>The <code><layout></code> element takes a mandatory class
attribute specifying the fully qualified name of the layout class to
instantiate. As with the <code><appender></code> element,
<code><layout></code> may contain other elements corresponding to
properties of the layout instance. Since it's such a common case, if
the layout class is <code>PatternLayout</code>, then the class
attribute can be omitted as specified by <a
href="onJoran.html#defaultClassMapping">default class mapping</a>
rules.
</p>
<p>The <code><encoder></code> element takes a mandatory class
attribute specifying the fully qualified name of the encoder class
to instantiate. Since it's such a common case, if the encoder class
is <code>PatternLayoutEncoder</code>, then the class attribute can
be omitted as specified by <a
href="onJoran.html#defaultClassMapping">default class mapping</a>
rules.
</p>
<p>Logging to multiple appenders is as easy as defining the various
appenders and referencing them in a logger, as the next
configuration file illustrates:
</p>
<p class="example">Example: Multiple loggers
(logback-examples/src/main/java/chapters/configuration/multiple.xml)</p>
<span class="asGroovy" onclick="return asGroovy('multiple');">View as .groovy</span>
<pre id="multiple" class="prettyprint source"><configuration>
<appender name="<b>FILE</b>" class="ch.qos.logback.core.FileAppender">
<file>myApp.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<appender name="<b>STDOUT</b>" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<b><appender-ref ref="FILE" /></b>
<b><appender-ref ref="STDOUT" /></b>
</root>
</configuration></pre>
<p>These configuration scripts define two appenders called
<em>FILE</em> and <em>STDOUT</em>. The <em>FILE</em> appender logs
to a file called <em>myApp.log</em>. The encoder for this appender
is a <code>PatternLayoutEncoder</code> that outputs the date, level,
thread name, logger name, file name and line number where the log
request is located, the message and line separator character(s).
The second appender called <code>STDOUT</code> outputs to the
console. The encoder for this appender outputs only the message
string followed by a line separator.
</p>
<p>The appenders are attached to the root logger by referencing them
by name within an <em>appender-ref</em> element. Note that each
appender has its own encoder. Encoders are usually not designed to
be shared by multiple appenders. The same is true for layouts. As
such, logback configuration files do not provide any syntactical
means for sharing encoders or layouts.
</p>
<h4 class="doAnchor" name="cumulative">Appenders accumulate
</h4>
<p>By default, <b>appenders are cumulative</b>: a logger will log to
the appenders attached to itself (if any) as well as all the
appenders attached to its ancestors. Thus, attaching the same
appender to multiple loggers will cause logging output to be
duplicated.
</p>
<p class="example">Example: Duplicate appender
(logback-examples/src/main/java/chapters/configuration/duplicate.xml)</p>
<span class="asGroovy" onclick="return asGroovy('duplicate');">View as .groovy</span>
<pre id="duplicate" class="prettyprint source"><configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="chapters.configuration">
<appender-ref ref="STDOUT" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>Running <code>MyApp3</code> with <em>duplicate.xml</em> will
yield the following output:
</p>
<p class="source">14:25:36.343 [main] INFO chapters.configuration.MyApp3 - Entering application.
14:25:36.343 [main] INFO chapters.configuration.MyApp3 - Entering application.
14:25:36.359 [main] DEBUG chapters.configuration.Foo - Did it again!
14:25:36.359 [main] DEBUG chapters.configuration.Foo - Did it again!
14:25:36.359 [main] INFO chapters.configuration.MyApp3 - Exiting application.
14:25:36.359 [main] INFO chapters.configuration.MyApp3 - Exiting application.</p>
<p>Notice the duplicated output. The appender named <em>STDOUT</em>
is attached to two loggers, to root and to
<em>chapters.configuration</em>. Since the root logger is the
ancestor of all loggers and <em>chapters.configuration</em> is the
parent of both <em>chapters.configuration.MyApp3</em> and
<em>chapters.configuration.Foo</em>, each logging request made with
these two loggers will be output twice, once because <em>STDOUT</em>
is attached to <em>chapters.configuration</em> and once because it
is attached to <em>root</em>.
</p>
<p>Appender additivity is not intended as a trap for new users. It
is quite a convenient logback feature. For instance, you can
configure logging such that log messages appear on the console (for
all loggers in the system) while messages only from some specific
set of loggers flow into a specific appender.
</p>
<p class="example">Example: Multiple appender
(logback-examples/src/main/java/chapters/configuration/restricted.xml)</p>
<span class="asGroovy" onclick="return asGroovy('restricted');">View as .groovy</span>
<pre id="restricted" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>myApp.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<logger name="chapters.configuration">
<appender-ref ref="FILE" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>In this example, the console appender will log all the messages
(for all loggers in the system) whereas only logging requests
originating from the <em>chapters.configuration</em> logger and its
children will go into the <em>myApp.log</em> file.
</p>
<h4 class="doAnchor" name="overrridingCumulativity">Overriding the
default cumulative behaviour</h4>
<p>In case the default cumulative behavior turns out to be
unsuitable for your needs, you can override it by setting the
additivity flag to false. Thus, a branch in your logger tree may
direct output to a set of appenders different from those of the rest
of the tree.
</p>
<p class="example">Example: Additivity flag
(logback-examples/src/main/java/chapters/configuration/additivityFlag.xml)</p>
<span class="asGroovy" onclick="return asGroovy('additivityFlag');">View as .groovy</span>
<pre id="additivityFlag" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>foo.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<logger name="chapters.configuration.Foo" <b>additivity="false"</b>>
<appender-ref ref="FILE" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>This example, the appender named <em>FILE</em> is attached to the
<em>chapters.configuration.Foo</em> logger. Moreover, the <em>chapters.configuration.Foo</em>
logger has its additivity flag set to false such that its logging
output will be sent to the appender named <em>FILE</em> but not to
any appender attached higher in the hierarchy. Other loggers remain
oblivious to the additivity setting of the <em>chapters.configuration.Foo</em>
logger. Running the <code>MyApp3</code> application with the
<em>additivityFlag.xml</em> configuration file will output results
on the console from the <em>chapters.configuration.MyApp3</em> logger. However,
output from the <em>chapters.configuration.Foo</em> logger will appear in the
<em>foo.log</em> file and only in that file.
</p>
<h3 class="doAnchor" name="contextName">Setting the context
name</h3>
<p>As mentioned <a href="architecture.html#LoggerContext">in an
earlier chapter</a>, every logger is attached to a logger
context. By default, the logger context is called
"default". However, you can set a different name with the help of
the <code><contextName></code> configuration directive. Note that
once set, the logger context name <a
href="../apidocs/ch/qos/logback/core/ContextBase.html#setName(java.lang.String)">cannot
be changed</a>. Setting the context name is a simple and
straightforward method in order to distinguish between multiple
applications logging to the same target.
</p>
<p class="example">Example: Set the context name and display it
(logback-examples/src/main/java/chapters/configuration/contextName.xml)</p>
<span class="asGroovy" onclick="return asGroovy('contextName');">View as .groovy</span>
<pre id="contextName" class="prettyprint source"><configuration>
<b><contextName>myAppName</contextName></b>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d <b>%contextName</b> [%t] %level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>This last example illustrates naming of the logger
context. Adding the <a
href="layouts.html#conversionWord">contextName conversion word</a>
in layout's pattern will output the said name.</p>
<!-- =============================================================== -->
<h3 class="doAnchor" name="variableSubstitution">Variable
substitution</h3>
<p><span class="label">Note</span> Earlier versions of this document
used the term "property substitution" instead of the term
"variable". Please consider both terms interchangeable although the
latter term conveys a clearer meaning.
</p>
<p>As in many scripting languages, logback configuration files
support definition and substitution of variables. Variables can be
defined within the configuration file itself, in an external file,
in an external resource or even computed and <a
href="#definingPropsOnTheFly">defined on the fly</a>.
</p>
<p class="highlight">Variable substitution can occur at any point in
a configuration file where a value can be specified.</p>
<p>Variable substitution can occur at any point in a configuration
file where a value can be specified. The syntax of variable
substitution is similar to that of Unix shells. The string between
an opening <em>${</em> and closing <em>}</em> is interpreted as a
reference to the <em>value</em> of the property. For property
<em>aName</em>, the string "${aName}" will be replaced with the
value held by the <em>aName</em> property.
</p>
<p>Variables have a <a href="#scopes">scope</a> (see below).</p>
<p>As they often come in handy, the HOSTNAME and CONTEXT_NAME
variables are automatically defined and have context scope.</p>
<h4 class="doAnchor" name="definingProps">Defining variables</h4>
<p>Variables can be defined one at a time in the configuration file
itself or loaded wholesale from an external properties file or an
external resource. For historical reasons, the XML element for
defining variables is <code><property></code> although in
logback 1.0.7 and later the element <code><variable></code> can
be used interchangeably.</p>
<p>The next example shows a variable declared at the beginning of
the configuration file. It is then used further down the file to
specify the location of the output file.
</p>
<p class="example">Example: Simple Variable substitution
(logback-examples/src/main/java/chapters/configuration/variableSubstitution1.xml)
</p>
<span class="asGroovy" onclick="return asGroovy('variableSubstitution1');">View as .groovy</span>
<pre id="variableSubstitution1" class="prettyprint source"><configuration>
<b><property name="USER_HOME" value="/home/sebastien" /></b>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<b><file>${USER_HOME}/myApp.log</file></b>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>The next example shows the use of a System property to achieve
the same result. The property is not declared in the configuration
file, thus logback will look for it in the System properties. Java
system properties can be set on the command line as shown next:
</p>
<p class="source">java -DUSER_HOME="/home/sebastien" MyApp2</p>
<p class="example">Example: System Variable substitution
(logback-examples/src/main/java/chapters/configuration/variableSubstitution2.xml)
</p>
<span class="asGroovy" onclick="return asGroovy('variableSubstitution2');">View as .groovy</span>
<pre id="variableSubstitution2" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<b><file>${USER_HOME}/myApp.log</file></b>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>When multiple variables are needed, it may be more convenient to
create a separate file that will contain all the variables. Here is
how one can do such a setup.
</p>
<p class="example">Example: Variable substitution using a
separate file
(logback-examples/src/main/java/chapters/configuration/variableSubstitution3.xml)
</p>
<span class="asGroovy" onclick="return asGroovy('variableSubstitution3');">View as .groovy</span>
<pre id="variableSubstitution3" class="prettyprint source"><configuration>
<b><property file="src/main/java/chapters/configuration/variables1.properties" /></b>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<b><file>${USER_HOME}/myApp.log</file></b>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>This configuration file contains a reference to a file named
<em>variables1.properties</em>. The variables contained in that
file will be read and then defined within local scope. Here is what
the <em>variable.properties</em> file might look like.
</p>
<em>Example: Variable file
(logback-examples/src/main/java/chapters/configuration/variables1.properties)</em>
<pre class="source">USER_HOME=/home/sebastien</pre>
<p>You may also reference a resource on the class path instead of a
file.</p>
<pre class="prettyprint source"><configuration>
<b><property resource="resource1.properties" /></b>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<b><file>${USER_HOME}/myApp.log</file></b>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<h4 class="doAnchor" name="scopes">Scopes</h4>
<p>A property can be defined for insertion in <em>local scope</em>,
in <em>context scope</em>, or in <em>system scope</em>. Local scope
is the default. Although it is possible to read variables from the
OS environment, it is not possible to write into the OS
environment.</p>
<p><span class="label">local scope</span> A property with local
scope exists from the point of its definition in a configuration
file until the end of interpretation/execution of said
configuration file. As a corollary, each time a configuration file
is parsed and executed, variables in local scope are defined
anew.</p>
<p><span class="label">context scope</span> A property with context
scope is inserted into the context and lasts as long as the context
or until it is cleared. Once defined, a property in context scope
is part of the context. As such, it is available in all logging
events, including those sent to remote hosts via serialization.
</p>
<p><span class="label">system scope</span> A property with system
scope is inserted into the JVM's system properties and lasts as
long as the JVM or until it is cleared.
</p>
<p class="highlight">Properties are looked up in the the local
scope first, in the context scope second, in the system properties
scope third, and in the OS environment last.
</p>
<p>During substitution, properties are looked up in the local scope
first, in the context scope second, in the system properties scope
third, and in the <a
href="http://docs.oracle.com/javase/tutorial/essential/environment/env.html">OS
environment</a> fourth and last.
</p>
<p>The <span class="attr">scope</span> attribute of the
<code><property></code> element, <code><define></code>
element or the <code><insertFromJNDI></code> element can be used
to set the scope of a property. The <span class="attr">scope</span>
attribute admits "local", "context" and "system" strings as
possible values. If not specified, the scope is always assumed to
be "local".
</p>
<p class="example">Example: A variable defined in "context" scope
(logback-examples/src/main/java/chapters/configuration/contextScopedVariable.xml)
</p>
<span class="asGroovy" onclick="return
asGroovy('contextScopedVariable');">View as .groovy</span>
<pre id="contextScopedVariable" class="prettyprint source"><configuration>
<property <b class="big">scope="context"</b> name="nodeId" value="firstNode" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<b><file>/opt/${nodeId}/myApp.log</file></b>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>In the above example, given that the <em>nodeId</em> property is
defined in the context scope, it will be available in every logging
event, even those sent to remote hosts via serialization.</p>
<h3 class="doAnchor" name="defaultValuesForVariables">Default values
for variables</h3>
<p>Under certain circumstances, it may be desirable for a variable
to have a default value if it is not declared or its value is
null. As in the <a
href="http://tldp.org/LDP/abs/html/parameter-substitution.html">Bash
shell</a>, default values can be specified using the <b>":-"</b>
operator. For example, assuming the variable named <em>aName</em> is
not defined, <code>"${aName<b>:-golden</b>}"</code> will be
interpreted as "golden".</p>
<h3 class="doAnchor" name="nestedSubst">Nested variables</h3>
<p>Variable nesting is fully supported. Both the name,
default-value and value definition of a variable can reference
other variables.</p>
<h4>value nesting</h4>
<p>The value definition of a variable can contain references to
other variables. Suppose you wish to use variables to specify not
only the destination directory but also the file name, and combine
those two variables in a third variable called "destination". The
properties file shown below gives an example.
</p>
<p class="example">Example: Nested variable references
(logback-examples/src/main/java/chapters/configuration/variables2.properties)</p>
<pre class="source">USER_HOME=/home/sebastien
fileName=myApp.log
<b>destination=${USER_HOME}/${fileName}</b></pre>
<p>Note that in the properties file above, "destination" is
composed from two other variables, namely "USER_HOME" and
"fileName".
</p>
<em>Example: Variable substitution using
a separate file
(logback-examples/src/main/java/chapters/configuration/variableSubstitution4.xml)</em>
<pre class="prettyprint source"><configuration>
<property file="variables2.properties" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<b><file>${destination}</file></b>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<h4>name nesting</h4>
<p>When referencing a variable, the variable name may contain a
reference to another variable. For example, if the variable named
"userid" is assigned the value "alice", then
"${${userid}.password}" references the variable with the name
"alice.password".</p>
<h4>default value nesting</h4>
<p>The default value of a variable can reference a another
variable. For example, assuming the variable 'id' is unassigned
and the variable 'userid' is assigned the value "alice", then the
expression "${id<b>:-</b>${userid}}" will return "alice".
</p>
<!-- ==============================================================
-->
<h3 class="doAnchor" name="hostname">HOSTNAME property</h3>
<p>As it often comes in handy, the <code>HOSTNAME</code> property is
defined automatically during configuration with context scope.</p>
<!-- ============================================================== -->
<h3 class="doAnchor" name="context_name">CONTEXT_NAME property</h3>
<p>As its name indicates, the <code>CONTEXT_NAME</code> property
corresponds to the name of the current logging context.</p>
<!-- ============================================================== -->
<h3 class="doAnchor" name="timestamp">Setting a timestamp</h3>
<p>The <em>timestamp</em> element can define a property according to
current date and time. The <em>timestamp</em> element is <a
href="appenders.html#uniquelyNamed">explained in a subsequent
chapter</a>.</p>
<!-- ============================================================== -->
<h3 class="doAnchor" name="definingPropsOnTheFly">Defining
properties on the fly</h3>
<p>You may define properties dynamically using the
<code><define></code> element. The define element takes two
mandatory attributes: <span class="attr">name</span> and <span
class="attr">class</span>. The <span class="attr">name</span>
attribute designates the name of the property to set whereas the
<span class="attr">class</span> attribute designates any class
implementing the <a
href="../xref/ch/qos/logback/core/spi/PropertyDefiner.html">PropertyDefiner</a>
interface. The value returned by the <code>getPropertyValue</code>()
method of the <code>PropertyDefiner</code> instance will be the
value of the named property. You may also specify a <a
href="#scopes">scope</a> for the named property by specifying a
<span class="attr">scope</span> attribute.
</p>
<p>Here is an example.</p>
<pre class="prettyprint source"><configuration>
<define name="rootLevel" class="a.class.implementing.PropertyDefiner">
<shape>round</shape>
<color>brown</color>
<size>24</size>
</define>
<root level="${rootLevel}"/>
</configuration></pre>
<p>In the above example, shape, color and size are properties of
"a.class.implementing.PropertyDefiner". As long as there is a setter
for a given property in your implementation of the
<code>PropertyDefiner</code> instance, logback will inject the
appropriate values as specified in the configuration file. </p>
<p>At the present time, logback does ships with two fairly simple
implementations of <code>PropertyDefiner</code>.
</p>
<table class="bodyTable striped">
<tr>
<th>Implementation name</th>
<th>Description</th>
</tr>
<tr>
<td><a
href="../apidocs/ch/qos/logback/core/property/FileExistsPropertyDefiner.html"><code>FileExistsPropertyDefiner</code></a>
</td>
<td>Set the named variable to "true" if the file specified by
<span class="prop">path</span> property exists, to "false"
otherwise.
</td>
</tr>
<tr>
<td><a
href="../apidocs/ch/qos/logback/core/property/FileExistsPropertyDefiner.html"><code>ResourceExistsPropertyDefiner</code></a>
</td>
<td>Set the named variable to "true" if the <span
class="prop">resource</span> specified by the user is available
on the class path, to "false" otherwise.
</td>
</tr>
</table>
<!-- ============================================================== -->
<h3 class="doAnchor" name="conditional">Conditional processing of
configuration files</h3>
<p>Developers often need to juggle between several logback
configuration files targeting different environments such as
development, testing and production. These configuration files have
substantial parts in common differing only in a few places. To avoid
duplication, logback supports conditional processing of
configuration files with the help of <code><if></code>,
<code><then></code> and <code><else></code> elements so that a
single configuration file can adequately target several
environments. Note that conditional processing requires the <a
href="../setup.html#janino">Janino library</a>.
</p>
<p>The general format for conditional statements is shown below.</p>
<pre class="prettyprint source">
<!-- if-then form -->
<if condition="some conditional expression">
<then>
...
</then>
</if>
<!-- if-then-else form -->
<if condition="some conditional expression">
<then>
...
</then>
<else>
...
</else>
</if></pre>
<p>The condition is a Java expression in which only context
properties or system properties are accessible. For a key passed as
argument, the <code>property</code>() or its shorter equivalent
<code>p</code>() methods return the String value of the property.
For example, to access the value of a property with key "k", you
would write <code>property("k")</code> or equivalently
<code>p("k")</code>. If the property with key "k" is undefined, the
property method will return the empty string and not null. This
avoids the need to check for null values.</p>
<p>The <code>isDefined()</code> method can be used to check whether
a property is defined. For example, to check whether the property
"k" is defined you would write <code>isDefined("k")</code>
Similarly, if you need to check whether a property is null, the
<code>isNull()</code> method is provided. Example:
<code>isNull("k")</code>.</p>
<pre class="prettyprint source"><configuration debug="true">
<b><if condition='property("HOSTNAME").contains("torino")'></b>
<b><then></b>
<appender name="CON" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level %logger{35} - %msg %n</pattern>
</encoder>
</appender>
<root>
<appender-ref ref="CON" />
</root>
<b></then></b>
<b></if></b>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${randomOutputDir}/conditional.log</file>
<encoder>
<pattern>%d %-5level %logger{35} - %msg %n</pattern>
</encoder>
</appender>
<root level="ERROR">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>Conditional processing is supported <em>anywhere</em> within the
<code><configuration></code> element. Nested if-then-else
statements are also supported. However, XML syntax is awfully
cumbersome and is ill suited as the foundation of a general purpose
programming language. Consequently, too many conditionals will
quickly render your configuration files incomprehensible to subsequent
readers, including yourself.
</p>
<!-- ============================================================== -->
<h3 class="doAnchor" name="insertFromJNDI">Obtaining variables from
JNDI</h3>
<p>Under certain circumstances, you may want to make use of
env-entries stored in JNDI. The <code><insertFromJNDI></code>
configuration directive extracts an env-entry stored in JNDI and
inserts the property in local scope with key specified by the <span
class="attr">as</span> attribute. As all properties, it is possible
to insert the new property into a <a href="#scopes">different
scope</a> with the help of the <em>scope</em> attribute.
</p>
<p class="example">Example: Insert as properties env-entries
obtained via JNDI
(logback-examples/src/main/java/chapters/configuration/insertFromJNDI.xml)</p>
<pre class="prettyprint source"><configuration>
<b><insertFromJNDI env-entry-name="java:comp/env/appName" as="<span class="green">appName"</span> /></b>
<b><contextName><span class="green">${appName}</span></contextName></b>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d ${CONTEXT_NAME} %level %msg %logger{50}%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="CONSOLE" />
</root>
</configuration></pre>
<p>In this last example, the "java:comp/env/appName" env-entry is
inserted as the <span class="variable">appName</span> property. Note
that the <code><contextName></code> directive sets the context
name based on the value of the <span class="variable">appName</span>
property inserted by the previous <code><insertFromJNDI></code>
directive.
</p>
<h3 class="doAnchor" name="fileInclusion">File inclusion</h3>
<p>Joran supports including parts of a configuration file from
another file. This is done by declaring a <code><include></code>
element, as shown below:
</p>
<p class="example">Example: File include
(logback-examples/src/main/java/chapters/configuration/containingConfig.xml)</p>
<pre class="prettyprint source"><configuration>
<b><include file="src/main/java/chapters/configuration/includedConfig.xml"/></b>
<root level="DEBUG">
<appender-ref ref="includedConsole" />
</root>
</configuration></pre>
<p>The target file MUST have its elements nested inside an
<code><included></code> element. For example, a
<code>ConsoleAppender</code> could be declared as:
</p>
<p class="example">Example: File include
(logback-examples/src/main/java/chapters/configuration/includedConfig.xml)</p>
<pre class="source"><b class="green big"><included></b>
<appender name="includedConsole" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>"%d - %m%n"</pattern>
</encoder>
</appender>
<b class="green big"></included></b></pre>
<p>Again, please note the mandatory
<code class="big green"><included></code> element.</p>
<p>The contents to include can be referenced as a file, as a
resource, or as a URL.</p>
<ul>
<li><b>As a file:</b><br/> To include a file use the <span
class="attr">file</span> attribute. You can use relative paths but
note that the current directory is defined by the application and
is not necessarily related to the path of the configuration
file.</li>
<li><p><b>As a resource:</b><br/> To include a resource, i.e a
file found on the class path, use the <span
class="attr">resource</span> attribute.</p>
<pre class="prettyprint source"><include resource="includedConfig.xml"/></pre>
</li>
<li><p><b>As a URL:</b><br/> To include the contents of a URL use
the <span class="attr">url</span> attribute.</p>
<pre class="prettyprint source"><include url="http://some.host.com/includedConfig.xml"/></pre>
</li>
</ul>
<p>If it cannot find the file to be included, logback will complain
by printing a status message. In case the included file is
optional, you can suppress the warning message by setting <span
class="attr">optional</span> attribute to <code>true</code> in the
<code><include></code> element.</p>
<pre class="prettyprint source"><include optional="true" ..../></pre>
<!-- ==================== ContextListener =================== -->
<h2 class="doAnchor" name="contextListener">Adding a context
listener</h2>
<p>Instances of the <a
href="../xref/ch/qos/logback/classic/spi/LoggerContextListener.html">LoggerContextListener</a>
interface listen to events pertaining to the lifecycle of a logger
context.
</p>
<p><code>JMXConfigurator</code> is one implementation of the
<code>LoggerContextListener</code> interface. It is described in a <a
href="jmxConfig.html">subsequent chapter</a>.
</p>
<h3 class="doAnchor"
name="LevelChangePropagator">LevelChangePropagator</h3>
<p>As of version 0.9.25, logback-classic ships with <a
href="../xref/ch/qos/logback/classic/jul/LevelChangePropagator.html">LevelChangePropagator</a>,
an implementation of <code>LoggerContextListener</code> which
propagates changes made to the level of any logback-classic logger
onto the java.util.logging framework. Such propagation eliminates
the performance impact of disabled log statements. Instances of <a
href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/logging/LogRecord.html?is-external=true">LogRecord</a>
will be sent to logback (via SLF4J) only for enabled log
statements. This makes it reasonable for real-world applications to
use the <a
href="http://www.slf4j.org/legacy.html#jul-to-slf4j">jul-to-slf4j</a>
bridge.
</p>
<p>The contextListener element can be used to install <code>LevelChangePropagator</code> as shown next.</p>
<pre class="prettyprint source"><configuration debug="true">
<b><contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"/></b>
....
</configuration></pre>
<p>Setting the <span class="option">resetJUL</span> property of
LevelChangePropagator will reset all previous level configurations
of all j.u.l. loggers. However, previously installed handlers will be
left untouched.</p>
<pre class="prettyprint source"><configuration debug="true">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<b><resetJUL>true</resetJUL></b>
</contextListener>
....
</configuration></pre>
<p>
</p>
<script src="../templates/footer.js" type="text/javascript"></script>
</div>
</body>
</html>
|