/usr/share/doc/liblogback-java/manual/layouts.html is in liblogback-java-doc 1:1.0.0-1.
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 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 | <!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 6: Layouts</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()">
<script type="text/javascript">prefix='../';</script>
<script type="text/javascript" src="../js/prettify.js"></script>
<script type="text/javascript" src="../js/dsl.js"></script>
<script src="../templates/header.js" type="text/javascript"></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">
<h1>Chapter 6: Layouts</h1>
<div class="quote">
<p>TCP implementations will follow a general principle of
robustness: be conservative in what you do, be liberal in what
you accept from others.
</p>
<p>—JON POSTEL, RFC 793</p>
</div>
<script src="../templates/creative.js" type="text/javascript"></script>
<script src="../templates/setup.js" type="text/javascript"></script>
<h2>What is a layout?</h2>
<p>In case you were wondering, layouts have nothing to do with
large estates in Florida. Layouts are logback components
responsible for transforming an incoming event into a String. The
<code>format()</code> method in the <a
href="../xref/ch/qos/logback/core/Layout.html"><code>Layout</code></a>
interface takes an object that represents an event (of any type)
and returns a String. A synopsis of the <code>Layout</code>
interface is shown below.
</p>
<pre class="prettyprint source">public interface Layout<E> extends ContextAware, LifeCycle {
String doLayout(E event);
String getFileHeader();
String getPresentationHeader();
String getFileFooter();
String getPresentationFooter();
String getContentType();
}</pre>
<p>This interface is rather simple and yet is sufficient for many
formatting needs. The Texan developer from Texas, whom you might
know from Joseph Heller's <em>Catch-22</em>, might exclaim: it
just takes five methods to implement a layout!!?
</p>
<h2>Logback-classic</h2>
<p>Logback-classic is wired to process only events of type
<a href="../xref/ch/qos/logback/classic/spi/ILoggingEvent.html">
<code>ch.qos.logback.classic.spi.ILoggingEvent</code></a>. This
fact will be apparent throughout this section.</p>
<h2><a name="writingYourOwnLayout"
href="#writingYourOwnLayout">Writing your own custom
Layout</a></h2>
<p>Let us implement a simple yet functional layout for the
logback-classic module that prints the time elapsed since the
start of the application, the level of the logging event, the
caller thread between brackets, its logger name, a dash followed
by the event message and a new line.
</p>
<p>Sample output might look like:</p>
<div class="source">10489 DEBUG [main] com.marsupial.Pouch - Hello world.</div>
<p>Here is a possible implementation, authored by the Texan developer:</p>
<em>Example: Sample implementation of a Layout
<a href="../xref/chapters/layouts/MySampleLayout.html">
(logback-examples/src/main/java/chapters/layouts/MySampleLayout.java)</a></em>
<pre class="prettyprint source">package chapters.layouts;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.LayoutBase;
public class MySampleLayout extends LayoutBase<ILoggingEvent> {
public String doLayout(ILoggingEvent event) {
StringBuffer sbuf = new StringBuffer(128);
sbuf.append(event.getTimeStamp() - event.getLoggingContextVO.getBirthTime());
sbuf.append(" ");
sbuf.append(event.getLevel());
sbuf.append(" [");
sbuf.append(event.getThreadName());
sbuf.append("] ");
sbuf.append(event.getLoggerName();
sbuf.append(" - ");
sbuf.append(event.getFormattedMessage());
sbuf.append(CoreConstants.LINE_SEP);
return sbuf.toString();
}
}</pre>
<p>Note that <code>MySampleLayout</code> extends <a
href="../xref/ch/qos/logback/core/LayoutBase.html">
<code>LayoutBase</code></a>. This class manages state common to
all layout instances, such as whether the layout is started or
stopped, header, footer and content type data. It allows the
developer to concentrate on the formatting expected from his/her
<code>Layout</code>. Note that the <code>LayoutBase</code> class
is generic. In its class declaration, <code>MySampleLayout</code>
extends <code>LayoutBase<ILoggingEvent></code>.
</p>
<p>The <code>doLayout(ILoggingEvent event)</code> method, i.e. the
only method in <code>MySampleLayout</code>, begins by
instantiating a <code>StringBuffer</code>. It proceeds by adding
various fields of the event parameter. The Texan from Texas was
careful to print the formatted form of the message. This is
significant if one or more parameters were passed along with
the logging request.
</p>
<p>After adding these various characters to the string buffer, the
<code>doLayout()</code> method converts the buffer into a
<code>String</code> and returns the resulting value.
</p>
<p>In the above example, the <code>doLayout</code> method ignores
any eventual exceptions contained in the event. In a real world
layout implementation, you would most probably want to print the
contents of exceptions as well.
</p>
<h3><a name="configuringYourOwnLayout"
href="#configuringYourOwnLayout">Configuring your custom
layout</a></h3>
<p>Custom layouts are configured as any other component. As
mentioned earlier, <code>FileAppender</code> and its sub-classes
expect an encoder. In order to fulfill this requirement, we pass
to <code>FileAppender</code> an instance of
<code>LayoutWrappingEncoder</code> which wraps our
<code>MySampleLayout</code>. Here is the configuration file:</p>
<em>Example: Configuration of MySampleLayout
(logback-examples/src/main/java/chapters/layouts/sampleLayoutConfig.xml)</em>
<span class="asGroovy" onclick="return asGroovy('sampleLayoutConfig');">View as .groovy</span>
<pre id="sampleLayoutConfig" class="prettyprint source"><configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<b><encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"></b>
<b><layout class="chapters.layouts.MySampleLayout" /></b>
<b></encoder></b>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>The sample application <a
href="../xref/chapters/layouts/SampleLogging.html">
<code>chapters.layouts.SampleLogging</code></a> configures logback
with the configuration script passed as its first argument and
then logs a debug message, followed by an error message. </p>
<p>To run this example issue the following command from within the
<em>logback-examples</em> directory.
</p>
<p class="command">java chapters.layouts.SampleLogging src/main/java/chapters/layouts/sampleLayoutConfig.xml</p>
<p> This will produce:</p>
<div class="source"><pre>0 DEBUG [main] chapters.layouts.SampleLogging - Everything's going well
0 ERROR [main] chapters.layouts.SampleLogging - maybe not quite...</pre></div>
<p>That was simple enough. The skeptic Pyrrho of Elea, who
insists that nothing is certain except perhaps uncertainty itself,
which is by no means certain either, might ask: how about a layout
with options? The reader shall find a slightly modified version
of our custom layout in <a
href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2.java</code></a>. As
mentioned throughout this manual, adding a property to a layout or
any other logback component is as simple as declaring a setter
method for the property.
</p>
<p>The <a
href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2</code></a>
class contains two properties. The first one is a prefix that can
be added to the output. The second property is used to choose
whether to display the name of the thread from which the logging
request was sent.
</p>
<p>Here is a copy of the <a
href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2</code></a>
class :</p>
<pre class="prettyprint source">package chapters.layouts;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.LayoutBase;
public class MySampleLayout2 extends LayoutBase<ILoggingEvent> {
String prefix = null;
boolean printThreadName = true;
<b>public void setPrefix(String prefix) {
this.prefix = prefix;
}
public void setPrintThreadName(boolean printThreadName) {
this.printThreadName = printThreadName;
}</b>
public String doLayout(ILoggingEvent event) {
StringBuffer sbuf = new StringBuffer(128);
<b>if (prefix != null) {
sbuf.append(prefix + ": ");
}</b>
sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime());
sbuf.append(" ");
sbuf.append(event.getLevel());
<b>if (printThreadName) {
sbuf.append(" [");
sbuf.append(event.getThreadName());
sbuf.append("] ");
} else {
sbuf.append(" ");
}</b>
sbuf.append(event.getLoggerName());
sbuf.append(" - ");
sbuf.append(event.getFormattedMessage());
sbuf.append(LINE_SEP);
return sbuf.toString();
}
}</pre>
<p>The addition of the corresponding setter method is all that is
needed to enable the configuration of a property. Note that the
<code>PrintThreadName</code> property is a boolean and not a
<code>String</code>. Configuration of logback components was
covered in detail in the <a
href="configuration.html">chapter on configuration</a>. The <a
href="onJoran.html">chapter on Joran</a> provides further detail. Here is
the configuration file tailor made for
<code>MySampleLayout2</code>.
</p>
<span class="asGroovy" onclick="return asGroovy('MySampleLayout2');">View as .groovy</span>
<pre id="MySampleLayout2" class="prettyprint source"><configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="chapters.layouts.MySampleLayout2">
<b><prefix>MyPrefix</prefix></b>
<b><printThreadName>false</printThreadName></b>
</layout>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p></p>
<h2><a name="ClassicPatternLayout"
href="#ClassicPatternLayout">PatternLayout</a></h2>
<p>Logback classic ships with a flexible layout called <a
href="../xref/ch/qos/logback/classic/PatternLayout.html">
<code>PatternLayout</code></a>. As all layouts,
<code>PatternLayout</code> takes a logging event and returns a
<code>String</code>. However, this <code>String</code> can be
customized by tweaking <code>PatternLayout</code>'s
conversion pattern.
</p>
<p>The conversion pattern of <code>PatternLayout</code> is closely
related to the conversion pattern of the <code>printf()</code>
function in the C programming language. A conversion pattern is
composed of literal text and format control expressions called
<em>conversion specifiers</em>. You are free to insert any literal
text within the conversion pattern. Each conversion specifier
starts with a percent sign '%' and is followed by optional
<em>format modifiers</em>, a <em>conversion word</em> and optional
parameters between braces. The conversion word controls the data
field to convert, e.g. logger name, level, date or thread
name. The format modifiers control field width, padding, and left
or right justification.
</p>
<p>As already mentioned on several occasions,
<code>FileAppender</code> and sub-classes expect an
encoder. Consequently, when used in conjunction with
<code>FileAppender</code> or its subclasses a
<code>PatternLayout</code> must be wrapped within an
encoder. Given that the
<code>FileAppender</code>/<code>PatternLayout</code> combination
is so common, logback ships with an encoder named
<code>PatternLayoutEncoder</code>, designed solely for the purpose
of wrapping a <code>PatternLayout</code> instance so that it can
be seen as encoder. Below is an example which programmatically
configures a <code>ConsoleAppender</code> with a
<code>PatternLayoutEncoder</code>:</p>
<em>
Example: Sample usage of a PatternLayout
<a href="../xref/chapters/layouts/PatternSample.html">
(logback-examples/src/main/java/chapters/layouts/PatternSample.java)</a>
</em>
<pre class="prettyprint source">package chapters.layouts;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
public class PatternSample {
static public void main(String[] args) throws Exception {
Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
LoggerContext loggerContext = rootLogger.getLoggerContext();
// we are not interested in auto-configuration
loggerContext.reset();
<b>PatternLayoutEncoder encoder = new PatternLayoutEncoder();</b>
<b>encoder.setContext(loggerContext);</b>
<b>encoder.setPattern("%-5level [%thread]: %message%n");</b>
<b>encoder.start();</b>
ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
appender.setContext(loggerContext);
appender.setEncoder(encoder);
appender.start();
rootLogger.addAppender(appender);
rootLogger.debug("Message 1");
rootLogger.warn("Message 2");
}
}</pre>
<p>In the above example, the conversion pattern is set to be
<b>"%-5level [%thread]: %message%n"</b>. A synopsis of conversion
word included in logback will be given shortly. Running
<code>PatternSample</code> application as:
</p>
<p class="source">java java chapters.layouts.PatternSample</p>
<p>will yield the following output on the console.</p>
<p class="source">DEBUG [main]: Message 1
WARN [main]: Message 2</p>
<p>Note that in the conversion pattern <b>"%-5level [%thread]:
%message%n"</b> there is no explicit separator between literal
text and conversion specifiers. When parsing a conversion pattern,
<code>PatternLayout</code> is capable of differentiating between
literal text (space characters, the brackets, colon character) and
conversion specifiers. In the example above, the conversion
specifier %-5level means the level of the logging event should be
left justified to a width of five characters. Format specifiers
will be explained below.
</p>
<p>In <code>PatternLayout</code>, parenthesis can be used to group
conversion patterns. <b>It follows that the '(' and ')' carry
special meaning and need to be escaped if intended to be used as
literals. </b> The special nature of parenthesis is further <a
href="#Parentheses">explained below</a>.
</p>
<p>As mentioned previously, certain conversion specifiers may
include optional parameters passed between braces. A sample
conversion specifier with options could be
<code>%logger{10}</code>. Here "logger" is the conversion word,
and 10 is the option. Options are <a href="#cwOptions">further
discussed below</a>.
</p>
<p>The recognized conversions words along with their options are
described in the table below. When multiple conversion words are
listed in the same table cell, they are considered as aliases.
</p>
<table class="bodyTable properties" border="0">
<tr>
<th><a name="conversionWord" href="#conversionWord">Conversion Word</a></th>
<th>Effect</th>
</tr>
<tr>
<td align="center">
<b>c</b>{<em>length</em>} <br />
<b>lo</b>{<em>length</em>} <br />
<b>logger</b>{<em>length</em>} <br />
</td>
<td>
Outputs the name of the logger at the origin of the logging
event.
<p>This conversion word can take an integer as its first and
only option. The converter's abbreviation algorithm will
shorten the logger name, usually without significant loss of
meaning. Setting the value of this option to zero has
special meaning. It will cause the conversion word to return
the sub-string right to the rightmost dot character in the
logger name. The next table provides examples of the
abbreviation algorithm in action.
</p>
<table class="bodyTable dark" border="0" cellpadding="8">
<tr>
<th>Conversion specifier</th>
<th>Logger name</th>
<th>Result</th>
</tr>
<tr>
<td>%logger</td>
<td>mainPackage.sub.sample.Bar</td>
<td>mainPackage.sub.sample.Bar</td>
</tr>
<tr>
<td>%logger{0}</td>
<td>mainPackage.sub.sample.Bar</td>
<td>Bar</td>
</tr>
<tr>
<td>%logger{5}</td>
<td>mainPackage.sub.sample.Bar</td>
<td>m.s.s.Bar</td>
</tr>
<tr>
<td>%logger{10}</td>
<td>mainPackage.sub.sample.Bar</td>
<td>m.s.s.Bar</td>
</tr>
<tr>
<td>%logger{15}</td>
<td>mainPackage.sub.sample.Bar</td>
<td>m.s.sample.Bar</td>
</tr>
<tr>
<td>%logger{16}</td>
<td>mainPackage.sub.sample.Bar</td>
<td>m.sub.sample.Bar</td>
</tr>
<tr>
<td>%logger{26}</td>
<td>mainPackage.sub.sample.Bar</td>
<td>mainPackage.sub.sample.Bar</td>
</tr>
</table>
<p>Please note that the rightmost segment in a logger name
is never abbreviated, even if its length is longer than the
<em>length</em> option. Other segments may be shortened to
at most a single character but are never removed.</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<b>C</b>{<em>length</em>} <br />
<b>class</b>{<em>length</em>} <br />
</td>
<td>
<p>Outputs the fully-qualified class name of the caller
issuing the logging request.
</p>
<p>Just like the <em>%logger</em> conversion word above,
this conversion takes an integer as an option to shorten
the class name. Zero carries special meaning and will cause
the simple class name to be printed without the package name
prefix. By default the class name is printed in full.
</p>
<p>Generating the caller class information is not
particularly fast. Thus, its use should be avoided unless
execution speed is not an issue.
</p>
</td>
</tr>
<tr>
<td align="center">
<b>contextName</b><br/>
<b>cn</b><br/></td>
<td>Outputs the name of the logger context to which the
logger at the origin of the event was attached to. </td>
</tr>
<tr class="alt">
<td align="center">
<b>d</b>{<em>pattern</em>} <br />
<b>date</b>{<em>pattern</em>} <br />
</td>
<td>
<p>Used to output the date of the logging event. The date
conversion word admits a pattern string as an option. The
pattern syntax is compatible with the format accepted by <a
href="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html"><code>java.text.SimpleDateFormat</code></a>.</p>
<p>You can specify the string <em>"ISO8601"</em> for the
ISO8601 date format. Note that the %date conversion word
defaults to the <a
href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601 date
format</a> in the absence of a pattern option.</p>
<p>Here are some sample option values. They assume that the
actual date is Friday 20th of October, 2006 and that the
author has returned to working on this document just after
lunch.</p>
<table class="bodyTable dark" cellpadding="8">
<tr>
<th>Conversion Pattern</th>
<th>Result</th>
</tr>
<tr>
<td>%d</td>
<td>2006-10-20 14:06:49,812</td>
</tr>
<tr>
<td>%date</td>
<td>2006-10-20 14:06:49,812</td>
</tr>
<tr>
<td>%date{ISO8601}</td>
<td>2006-10-20 14:06:49,812</td>
</tr>
<tr>
<td>%date{HH:mm:ss.SSS}</td>
<td>14:06:49.812</td>
</tr>
<tr>
<td>%date{dd MMM yyyy ;HH:mm:ss.SSS}</td>
<td>20 oct. 2006;14:06:49.812 </td>
</tr>
</table>
<p>In addition to the date pattern, this converter admits a
second option as the timezone. Thus, the
'%date{HH:mm:ss.SSS,Australia/Perth} would print the time in
the time zone of Perth, Australia, the world's most isolated
city.
</p>
<p>Given that the comma ',' character is the option
separator, the pattern string [HH:mm:ss,SSS] will print the
time in the [SSS] time zone which does not exist. Thus, the
time will be printed in the default GMT timezone. If you
wish to include a comma in your date pattern, then simply
enclose the pattern between quotes. For example,
%date{<b>"</b>HH:mm:ss,SSS<b>"</b>}.
</p>
</td>
</tr>
<tr>
<td align="center">
<b>F / file</b>
</td>
<td>
<p>Outputs the file name of the Java source file where the
logging request was issued.
</p>
<p>Generating the file information is not particularly fast.
Thus, its use should be avoided unless execution speed is
not an issue.
</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<b>caller{depth}</b>
<b>caller{depth, evaluator-1, ... evaluator-n}</b>
</td>
<td>
<p>Outputs location information of the caller which
generated the logging event.
</p>
<p>The location information depends on the JVM
implementation but usually consists of the fully qualified
name of the calling method followed by the caller's source,
the file name and line number between parentheses.
</p>
<p>A integer can be added to the <em>caller</em> conversion
specifier's options to configure the depth of the
information to be displayed.
</p>
<p>For example, <b>%caller{2}</b> would display the
following excerpt:</p>
<pre class="source white_bg">0 [main] DEBUG - logging statement
Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)
Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)</pre>
<p>And <b>%caller{3}</b> would display this other excerpt:</p>
<pre class="source white_bg">16 [main] DEBUG - logging statement
Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)
Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)
Caller+2 at mainPackage.ConfigTester.main(ConfigTester.java:38)</pre>
<p>This conversion word can also use evaluators to test
logging events against a given criterion before creating the
output. For example, using <b>%caller{3,
CALLER_DISPLAY_EVAL}</b> will display three lines of
stacktrace, only if the evaluator called
<em>CALLER_DISPLAY_EVAL</em> returns a <b>positive</b>
answer.
</p>
<p>Evaluators are described below.</p>
</td>
</tr>
<tr>
<td align="center">
<b>L / line</b>
</td>
<td>
<p>Outputs the line number from where the logging
request was issued.
</p>
<p>Generating the line number information is not particularly
fast. Thus, its use should be avoided unless execution
speed is not an issue.
</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<b>m / msg / message</b>
</td>
<td>
<p>Outputs the application-supplied message associated with
the logging event.
</p>
</td>
</tr>
<tr>
<td align="center">
<b>M / method</b>
</td>
<td>
<p>
Outputs the method name where the logging
request was issued.
</p>
<p>
Generating the method name is not particularly fast.
Thus, its use should be avoided unless
execution speed is not an issue.
</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<b>n</b>
</td>
<td>
<p>
Outputs the platform dependent line separator
character or characters.
</p>
<p>
This conversion word offers practically the
same performance as using non-portable line
separator strings such as "\n", or "\r\n". Thus,
it is the preferred way of specifying a line
separator.
</p>
</td>
</tr>
<tr>
<td align="center">
<b>p / le / level</b>
</td>
<td>Outputs the level of the logging event.</td>
</tr>
<tr class="alt">
<td align="center">
<b>r / relative</b>
</td>
<td>
Outputs the number of milliseconds elapsed
since the start of the application until the
creation of the logging event.
</td>
</tr>
<tr>
<td align="center">
<b>t / thread</b>
</td>
<td>
Outputs the name of the thread that generated
the logging event.
</td>
</tr>
<tr class="alt">
<td align="center">
<b>X</b>{<em>key</em>} <br />
<b>mdc</b>{<em>key</em>} <br />
</td>
<td>
<p>
Outputs the MDC (mapped diagnostic
context) associated with the thread that
generated the logging event.
</p>
<p>If the <b>mdc</b> conversion word is followed by a key
between braces, as in <b>%mdc{clientNumber}</b>, then the
value in the MDC corresponding to the key will be output.
</p>
<p>If no option is given, then the entire content of the MDC
will be output in the format "key1=val1, key2=val2".
</p>
<p>See the <a href="mdc.html">chapter on MDC</a> for more
details.
</p>
</td>
</tr>
<tr>
<td align="center">
<b>ex</b>{<em>depth</em>} <br />
<b>exception</b>{<em>depth</em>} <br />
<b>throwable</b>{<em>depth</em>} <br />
<br />
<b>ex</b>{depth, evaluator-1, ..., evaluator-n} <br />
<b>exception</b>{depth, evaluator-1, ..., evaluator-n} <br />
<b>throwable</b>{depth, evaluator-1, ..., evaluator-n}
</td>
<td>
<p>Outputs the stack trace of the exception
associated with the logging event, if any. By default the
full stack trace will be output.
</p>
<p>The <em>throwable</em> conversion word can followed by one of
the following options:
</p>
<ul>
<li><em>short</em>: prints the first line of the stack trace</li>
<li><em>full</em>: prints the full stack trace</li>
<li>Any integer: prints the given number of lines of the stack trace</li>
</ul>
<p>Here are some examples:</p>
<table class="bodyTable">
<tr class="a">
<th>Conversion Pattern</th>
<th>Result</th>
</tr>
<tr class="b">
<td>%ex</td>
<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)</pre></td>
</tr>
<tr class="a">
<td>%ex{short}</td>
<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)</pre></td>
</tr>
<tr class="b">
<td>%ex{full}</td>
<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)</pre></td>
</tr>
<tr class="a">
<td>%ex{2}</td>
<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)</pre></td>
</tr>
</table>
<p>This conversion word can also use evaluators to test
logging events against a given criterion before creating the
output. For example, using <b>%ex{full, EX_DISPLAY_EVAL}</b>
will display the full stack trace of the exception only if
the evaluator called <em>EX_DISPLAY_EVAL</em> returns a
<b>negative</b> answer. Evaluators are described further
down in this document.
</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<a name="xThrowable" href="#xThrowable">
<b>xEx</b>{<em>depth</em>} <br />
<b>xException</b>{<em>depth</em>} <br />
<b>xThrowable</b>{<em>depth</em>} <br />
<br />
<b>xEx</b>{depth, evaluator-1, ..., evaluator-n} <br />
<b>xException</b>{depth, evaluator-1, ..., evaluator-n} <br />
<b>xThrowable</b>{depth, evaluator-1, ..., evaluator-n}
</a>
</td>
<td>
<p>Same as the %throwable conversion word above with the
addition of class packaging information.</p>
<p>If you do not specify %xThrowable or another
throwable-related conversion word in the conversion pattern,
<code>PatternLayout</code> will automatically add it as the
last conversion word, on account of the importance of stack
trace information. The $nopex conversion word can be
substituted for %xThrowable, if you do not wish stack
trace information to be displayed. See also the %nopex
conversion word.
</p>
<p>At the end of each stack frame of the exception, a string
consisting of the jar file containing the relevant class
followed by the "Implementation-Version" as found in that
jar's manifest will be added. This innovative technique was
<a
href="http://macstrac.blogspot.com/2008/09/better-stack-traces-in-java-with-log4j.html">originally suggested
by James Strachan</a>. If the information is uncertain, then
the class packaging data will be preceded by a tilde, i.e.
the '~' character.
</p>
<p>Here is an example:</p>
<p class="source small">java.lang.NullPointerException
at com.xyz.Wombat(Wombat.java:57) <b><span class="red">~</span>[wombat-1.3.jar:1.3]</b>
at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_06]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_06]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.5.0_06]
at java.lang.reflect.Method.invoke(Method.java:585) ~[na:1.5.0_06]
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59) [junit-4.4.jar:na]
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98) [junit-4.4.jar:na]
...etc </p>
<p>Logback goes to great lengths to ensure that the class
packaging information it displays is correct, even in
arbitrarily complex class loader hierarchies. However, when
it is unable to guarantee the absolute correctness of the
information, then it will prefix the data with a tilde, i.e.
the '~' character. Thus, it is theoretically possible for
the printed class packaging information to differ from the
real class packaging information. So, in the above example,
given that packaging data for the Wombat class is preceded
by a tilde, it is possible that the correct packaging data is
in reality [wombat.jar:1.7].
</p>
<p><a
href="http://jira.qos.ch/browse/LBCLASSIC-212">Feedback from
users</a> indicates that Netbeans chokes on packaging
information. If you are a Netbeans user, then you should
disable packaging information in stack traces by adding
"%ex" at the end of of your conversion pattern. For example,
"%d %logger - %m%n" should be rewritten as "%d %logger -
%m%n<b>%ex</b>"
</p>
</td>
</tr>
<tr>
<td align="center">
<b>nopex</b> <br />
<b>nopexception</b>
</td>
<td>
<p>Although it <em>pretends</em> to handle stack trace data,
this conversion word does not output any data, thus,
effectively ignoring exceptions.
</p>
<p>The %nopex conversion word allows the user to override
<code>PatternLayout</code>'s internal safety mechanism which
silently adds the %xThrowable conversion keyword in the absence of
another conversion word handling exceptions.
</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<b>marker</b>
</td>
<td>
<p>Outputs the marker associated with the logger
request.</p>
<p>In case the marker contains children markers, the
converter displays the parent as well as childrens' names
according to the format shown below.
</p>
<p>
<em>parentName [ child1, child2 ]</em>
</p>
</td>
</tr>
<tr>
<td align="center">
<b>property{key}</b>
</td>
<td>
<p>Outputs the value associated with a context
property named <em>key</em>. If <em>key</em> is not a
property of the logger context, then <em>key</em> will be
looked up in the System properties. </p>
<p>There is no default value for <em>key</em>. If it is
omitted, the returned value will be "Property_HAS_NO_KEY",
expliciting the error condition.</p>
</td>
</tr>
<tr class="alt">
<td align="center">
<a name="replace" href="#replace"><b>replace(<em>p</em>){r, t}</b></a>
</td>
<td>
<p>Replaces occurrences of 'r', a regex, with its
replacement 't' in the string produces by the sub-pattern
'p'. For example, "%replace(%msg){'\s', ''}" will remove all
spaces contained in the event message.
</p>
<p>The pattern 'p' can be arbitrarily complex and in
particular can contain multiple conversion keywords. For
instance, "%replace(%logger %msg){'\.', '/'}" will replace
all dots in the logger or the message of the event with a
forward slash.
</p>
</td>
</tr>
<tr>
<td align="center">
<a name="rootException" href="#rootException">
<b>rEx</b>{<em>depth</em>} <br />
<b>rootException</b>{<em>depth</em>} <br />
<br />
<b>rEx</b>{depth, evaluator-1, ..., evaluator-n} <br />
<b>rootException</b>{depth, evaluator-1, ..., evaluator-n}</a>
</td>
<td>
<p>Outputs the stack trace of the exception associated with
the logging event, if any. The root cause will be output
first instead of the standard "root cause last". Here is a
sample output (edited for space):
</p>
<pre class="small">java.lang.NullPointerException
at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3]
at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]
Wrapped by: org.springframework.BeanCreationException: Error creating bean with name 'wombat':
at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248) [spring-2.0.jar:2.0]
at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170) [spring-2.0.jar:2.0]
at org.apache.catalina.StandardContext.listenerStart(StandardContext.java:3934) [tomcat-6.0.26.jar:6.0.26]
</pre>
<p>The %rootException converter admits the same optional
parameters as the %xException converter described above,
including depth and eveluators. It outputs also packaging
information. In short, %rootException is very similar to
%xException, only the order of exception output is reversed.
</p>
<p>Tomasz Nurkiewicz, the author of %rootException converter,
documents his contribution in a blog entry entitled <a
href="http://nurkiewicz.blogspot.com/2011/09/logging-exceptions-root-cause-first.html">"Logging
exceptions root cause first"</a>.</p>
</td>
</tr>
</table>
<h4>% character has special meaning</h4>
<p>Given that in the context of conversion patterns the percent
sign carries special meaning, in order to include it as a literal,
it needs to be escaped with a backslash, e.g. "%d %p <b>\%</b>
%m%n".
</p>
<h4>Restrictions on literals immediately following conversion
words</h4>
<p>In most cases literals naturally contain spaces or other
delimiting characters so that they are not confused with
conversion words. For example, the pattern
"%level [%thread] - %message%n" contains the string
literals <code>" ["</code> and
<code>"] - "</code>. However, if a character which can
be part of a java identifier immediately follows a conversion
word, logback's pattern parser will be fooled into thinking that
the literal is part of the conversion word. For example, the
pattern "%date<b>%nHello</b>" will be interpreted as two
conversion words %date and %nHello and since %nHello is not a
known conversion word, logback will output %PARSER_ERROR[nHello]
for %nHello. If you wish the string literal "Hello" to immediately
separate %n and Hello, pass an empty argument list to %n. For
example, "%date<b>%n{}</b>Hello" will be interpreted as %date
followed by %n followed by the literal "Hello".
</p>
<h2><a name="formatModifiers" href="#formatModifiers">Format
modifiers</a></h2>
<p>By default the relevant information is output as-is. However,
with the aid of format modifiers it is possible to change the
minimum and maximum width and the justifications of each data
field.
</p>
<p>The optional format modifier is placed between the percent sign
and the conversion character or word.
</p>
<p>The first optional format modifier is the <em>left
justification flag</em> which is just the minus (-)
character. Then comes the optional <em>minimum field width</em>
modifier. This is a decimal constant that represents the minimum
number of characters to output. If the data item contains fewer
characters, it is padded on either the left or the right until the
minimum width is reached. The default is to pad on the left (right
justify) but you can specify right padding with the left
justification flag. The padding character is space. If the data
item is larger than the minimum field width, the field is expanded
to accommodate the data. The value is never truncated.
</p>
<p>This behavior can be changed using the <em>maximum field
width</em> modifier which is designated by a period followed by a
decimal constant. If the data item is longer than the maximum
field, then the extra characters are removed from the
<em>beginning</em> of the data item. For example, if the maximum
field width is eight and the data item is ten characters long,
then the first two characters of the data item are dropped. This
behavior deviates from the printf function in C where truncation
is done from the end.
</p>
<p>Truncation from the end is possible by appending a minus
character right after the period. In that case, if the maximum
field width is eight and the data item is ten characters long,
then the last two characters of the data item are dropped.
</p>
<p>Below are various format modifier examples for the logger
conversion specifier.
</p>
<table class="bodyTable" border="0" cellpadding="8">
<tr>
<th>Format modifier</th>
<th>Left justify</th>
<th>Minimum width</th>
<th>Maximum width</th>
<th>Comment</th>
</tr>
<tr class="a">
<td align="center">%20logger</td>
<td align="center">false</td>
<td align="center">20</td>
<td align="center">none</td>
<td>
Left pad with spaces if the logger name is less
than 20 characters long.
</td>
</tr>
<tr class="b">
<td align="center">%-20logger</td>
<td align="center">true</td>
<td align="center">20</td>
<td align="center">none</td>
<td>
Right pad with spaces if the logger name is less
than 20 characters long.
</td>
</tr>
<tr class="a">
<td align="center">%.30logger</td>
<td align="center">NA</td>
<td align="center">none</td>
<td align="center">30</td>
<td>
Truncate from the beginning if the logger name is
longer than 30 characters.
</td>
</tr>
<tr class="b">
<td align="center">%20.30logger</td>
<td align="center">false</td>
<td align="center">20</td>
<td align="center">30</td>
<td>
Left pad with spaces if the logger name is shorter
than 20 characters. However, if logger name is
longer than 30 characters, then truncate from the
beginning.
</td>
</tr>
<tr class="a">
<td align="center">%-20.30logger</td>
<td align="center">true</td>
<td align="center">20</td>
<td align="center">30</td>
<td>
Right pad with spaces if the logger name is shorter
than 20 characters. However, if logger name is
longer than 30 characters, then truncate from the
<em>beginning</em>.
</td>
</tr>
<tr class="b">
<td align="center">%.-30logger</td>
<td align="center">NA</td>
<td align="center">none</td>
<td align="center">30</td>
<td>
Truncate from the <em>end</em> if the logger name is
longer than 30 characters.
</td>
</tr>
</table>
<p>The table below list examples for format modifier
truncation. Please note that the square brackets, i.e the pair of "[]"
characters, are not part of the output. They are used to delimit
the width of output.</p>
<table class="bodyTable" border="0" cellpadding="8">
<tr>
<th>Format modifier</th>
<th>Logger name</th>
<th>Result</th>
</tr>
<tr class="b">
<td align="center">[%20.20logger]</td>
<td align="center">main.Name</td>
<td align="center"><pre>[ main.Name]</pre></td>
</tr>
<tr class="a">
<td align="center">[%-20.20logger]</td>
<td align="center">main.Name</td>
<td align="center"><pre>[main.Name ]</pre></td>
</tr>
<tr class="a">
<td align="center">[%10.10logger]</td>
<td align="center">main.foo.foo.bar.Name</td>
<td align="center"><pre>[o.bar.Name]</pre></td>
</tr>
<tr class="b">
<td align="center">[%10.-10logger]</td>
<td align="center">main.foo.foo.bar.Name</td>
<td align="center"><pre>[main.foo.f]</pre></td>
</tr>
</table>
<h3><a name="oneLetterLevel" href="#oneLetterLevel">Output just
one letter for the level</a></h3>
<p>Instead of printing TRACE, DEBUG, WARN, INFO or ERROR for the
level, you may want to print just T, D, W, I and E. You could
write a <a href="#customConversionSpecifier">custom converter</a>
for this purpose, or simply make use of format modifiers (just
discussed) to shorten the level value to a single character. The
appropriate conversion specifier would be
"<code>%.-1level</code>".
</p>
<h2><a name="cwOptions" href="#cwOptions">Conversion word
options</a></h2>
<p>A conversion specifier can be followed by options. The are
always declared between braces. We have already seen some of the
possibilities offered by options, for instance in conjunction with
the MDC conversion specifier, as in: <em>%mdc{someKey}</em>.
</p>
<p>A conversion specifier might have more than one option. For
example, a conversion specifier that makes use of evaluators,
which will be covered soon, may add evaluator names to the option
list, as shown below:</p>
<pre class="prettyprint source"><pattern>%-4relative [%thread] %-5level - %msg%n \
<b>%caller{2, DISP_CALLER_EVAL, OTHER_EVAL_NAME, THIRD_EVAL_NAME}</b></pattern></pre>
<p>If the option includes special characters such as a braces, spaces or
commas, you can enclose it between single or double quotes. For
example, consider the next pattern.</p>
<pre class="prettyprint source"><pattern>%-5level - %replace(%msg)<b>{'\d{14,16}', 'XXXX'}</b>%n</pattern></pre>
<p>We pass the options <code>\d{16}</code> and <code>XXXX</code>
to the <code>replace</code> conversion word. It replaces any
sequence of 14, 15 or 16 digits contained in the message with XXXX
effectively obfuscating credit card numbers. Note that "\d" which
is a shorthand for a single digit in regular expressions. The
"{14,16\}" is interpreted as "{14, 16}", that is, repeat the
previous item at least 14 but at most 16 times.
</p>
<h2><a name="Parentheses" href="#Parentheses">Parentheses are
special</a></h2>
<p>In logback, parentheses within the pattern string are treated
as grouping tokens. Thus, it is possible to group a sub-pattern
and apply formatting directives on that sub-pattern. As of version
0.9.27, logback supports composite conversion words such as <a
href="#replace">%replace</a> which can transform sub-patterns.
</p>
<p>For example, the pattern</p>
<p class="source"><b>%-30(</b>%d{HH:mm:ss.SSS} [%thread]<b>)</b> %-5level %logger{32} - %msg%n</p>
<p>will group the output generated by the sub-pattern
"%d{HH:mm:ss.SSS} [%thread]" so that it is right-padded if less
than 30 characters.
</p>
<p>If without the grouping the output was</p>
<p class="source">13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Classload hashcode is 13995234
13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Initializing for ServletContext
13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Trying platform Mbean server
13:09:30 [pool-1-thread-1] INFO ch.qos.logback.demo.LoggingTask - Howdydy-diddly-ho - 0
13:09:38 [btpool0-7] INFO c.q.l.demo.lottery.LotteryAction - Number: 50 was tried.
13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Beginning to factor.
13:09:40 [btpool0-7] DEBUG c.q.l.d.prime.NumberCruncherImpl - Trying 2 as a factor.
13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Found factor 2
</p>
<p>with the "%-30()" grouping it would be</p>
<p class="source">13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Classload hashcode is 13995234
13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Initializing for ServletContext
13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Trying platform Mbean server
13:09:30 [pool-1-thread-1] INFO ch.qos.logback.demo.LoggingTask - Howdydy-diddly-ho - 0
13:09:38 [btpool0-7] INFO c.q.l.demo.lottery.LotteryAction - Number: 50 was tried.
13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Beginning to factor.
13:09:40 [btpool0-7] DEBUG c.q.l.d.prime.NumberCruncherImpl - Trying 2 as a factor.
13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Found factor 2
</p>
<p>The latter form is more comfortable to read.</p>
<p>If you need to treat the parenthesis character as a literal, it
needs to be escaped by preceding each parenthesis with a
backslash. As in, <b>\(</b>%d{HH:mm:ss.SSS}
[%thread]<b>\)</b>.
</p>
<h2><a name="Evaluators" href="#Evaluators">Evaluators</a></h2>
<p>As mentioned above, option lists come in handy when a
conversion specifier is required to behave dynamically based on
one or more
<a href="../xref/ch/qos/logback/core/boolex/EventEvaluator.html">
<code>EventEvaluator</code></a> objects.
<code>EventEvaluator</code> objects have the responsibility to
determine whether a given logging event matches the criteria of the
evaluator.
</p>
<p>Let us review an example involving a
<code>EventEvaluator</code>. The next configuration file outputs
the logging events to the console, displaying date, thread, level,
message and caller data. Given that extracting the caller data of
a logging event is on the expensive side, we will do so only when
the logging request originates from a specific logger, and when
the message contains a certain string. Thus, we make sure that only
specific logging requests will have their caller information
generated and displayed. In other cases, where the caller data is
superfluous, we will not penalize application performance.
</p>
<p>Evaluators and in particular <em>evaluation expressions</em>
are presented in a <a
href="filters.html#evalutatorFilter">dedicated section of the
chapter on filters</a> which you MUST read if you want to use
evaluators in any meaningful way. Also note that the examples below
are implicitly based on <code>JaninoEventEvaluator</code> which
requires the <a
href="http://docs.codehaus.org/display/JANINO/Home">Janino
library</a>. Please see the <a
href="../setup.html#janino">corresponding section</a> of the setup
document.</p>
<em>
Example: Sample usage of EventEvaluators
(logback-examples/src/main/java/chapters/layouts/callerEvaluatorConfig.xml)
</em>
<span class="asGroovy" onclick="return asGroovy('callerEvaluatorConfig');">View as .groovy</span>
<pre id="callerEvaluatorConfig" class="prettyprint source"><configuration>
<b><evaluator name="DISP_CALLER_EVAL">
<expression>logger.contains("chapters.layouts") &amp;&amp; \
message.contains("who calls thee")</expression>
</evaluator></b>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%-4relative [%thread] %-5level - %msg%n<b>%caller{2, DISP_CALLER_EVAL}</b>
</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>The above evaluation expression matches events which emanate
from a logger with a name containing the string "chapters.layouts"
and the message contains the string "who calls thee". Due to XML
encoding rules, the & character cannot be written as is, and
needs to be escaped as &amp;.</p>
<p>The following class makes use of some of the characteristics
mentioned in above configuration file.</p>
<p><em>
Example: Sample usage of EventEvaluators
<a href="../xref/chapters/layouts/CallerEvaluatorExample.html">
(logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java)</a>
</em>
</p>
<pre class="prettyprint source">package <b>chapters.layouts</b>;
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 CallerEvaluatorExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(CallerEvaluatorExample.class);
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
configurator.doConfigure(args[0]);
} catch (JoranException je) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
for (int i = 0; i < 5; i++) {
if (i == 3) {
logger.debug(<b>"who calls thee</b>?");
} else {
logger.debug("I know me " + i);
}
}
}
}</pre>
<p>The above application does nothing particularly fancy. Five
logging requests are issued, the third one emitting the message
"who calls thee?"
</p>
<p>The command</p>
<p class="source">java chapters.layouts.CallerEvaluatorExample src/main/java/chapters/layouts/callerEvaluatorConfig.xml</p>
<p>will yield</p>
<div class="source"><pre>0 [main] DEBUG - I know me 0
0 [main] DEBUG - I know me 1
0 [main] DEBUG - I know me 2
0 [main] DEBUG - who calls thee?
Caller+0 at chapters.layouts.CallerEvaluatorExample.main(CallerEvaluatorExample.java:28)
0 [main] DEBUG - I know me 4</pre></div>
<p>When a logging request is issued, the corresponding logging
event is evaluated. Only the third logging event matches the
evaluation criteria, causing its caller data to be displayed. For
other logging events, the evaluation criteria do not match and no
caller data is printed.
</p>
<p>One can change the expression to correspond a real world
scenario. For instance, one could combine the logger name and
request level. Thus, logging requests of level <em>WARN</em> and
up, originating from a sensitive part of an application, e.g. a
financial transaction module, would have their caller data
displayed.
</p>
<p><b>Important:</b> With the <em>caller</em> conversion word,
caller data is output when <em>the expression evaluates to
<b>true</b>.</em></p>
<p>Let us consider at a different situation. When exceptions are
included in a logging request, their stack trace is also
output. However, one might want to suppress the stack trace for
some specific exceptions.
</p>
<p>The Java code shown below creates three log requests, each with
an exception. The second exception is different from the others:
it contains the string "do not display this" and it is of type
<code>chapters.layouts.TestException</code>. As its message
commands, let us now prevent the second exception from being
printed.</p>
<p><em>
Example: Sample usage of EventEvaluators
<a href="../xref/chapters/layouts/ExceptionEvaluatorExample.html">
(logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java)</a>
</em>
</p>
<pre class="prettyprint source">package chapters.layouts;
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 ExceptionEvaluatorExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(ExceptionEvaluatorExample.class);
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(args[0]);
} catch (JoranException je) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
for (int i = 0; i < 3; i++) {
if (i == 1) {
logger.debug("logging statement " + i, new TestException(
"do not display this"));
} else {
logger.debug("logging statement " + i, new Exception("display"));
}
}
}
}</pre>
<p>In the next configuration file, the evaluation expression
matches events containing a throwable of type
<code>chapters.layouts.TextException</code>, precisely the type of
exceptions we wish to suppress.
</p>
<em>
Example: Sample usage of EventEvaluators
(logback-examples/src/main/java/chapters/layouts/exceptionEvaluatorConfig.xml)
</em>
<pre class="prettyprint source"><configuration>
<b><evaluator name="DISPLAY_EX_EVAL">
<expression>throwable != null &amp;&amp; throwable instanceof \
chapters.layouts.TestException</expression>
</evaluator></b>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder
<pattern>%msg%n<b>%ex{full, DISPLAY_EX_EVAL}</b></pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>With this configuration, each time an instance of the
<em>chapters.layouts.TestException</em> is included within a logging
request, the stack trace will be suppressed.
</p>
<p>Launching the command</p>
<p class="source">java chapters.layouts.ExceptionEvaluatorExample src/main/java/chapters/layouts/exceptionEvaluatorConfig.xml</p>
<p>will yield</p>
<p class="source">logging statement 0
java.lang.Exception: display
at chapters.layouts.ExceptionEvaluatorExample.main(ExceptionEvaluatorExample.java:43) [logback-examples-0.9.19.jar:na]
logging statement 1
logging statement 2
java.lang.Exception: display
at chapters.layouts.ExceptionEvaluatorExample.main(ExceptionEvaluatorExample.java:43) [logback-examples-0.9.19.jar:na]</p>
<p>Notice how the second log statement has no stack trace. We
effectively suppressed the stack trace for the
<code>TextException</code>. The text between square brackets at
the end of each stack trace line is <a
href="#xThrowable">packaging information</a> discussed
earlier.</p>
<p><b>Important:</b> With the <b><em>%ex</em></b> conversion
specifier, the stack trace is displayed when <em>the expression
evaluates to <b>false</b>.</em></p>
<h2><a name="customConversionSpecifier"
href="#customConversionSpecifier">Creating a custom conversion
specifier</a></h2>
<p>Up to this point we have presented the built-in conversion
words in <code>PatternLayout</code>. But it is also possible to
add conversion words of your own making.</p>
<p>Building a custom conversion specifier consists of two steps.
</p>
<p>First, you must extend the <code>ClassicConverter</code>
class. <a
href="../xref/ch/qos/logback/classic/pattern/ClassicConverter.html">
<code>ClassicConverter</code></a> objects are responsible for
extracting information out of <code>ILoggingEvent</code> instances
and producing a String. For example,
<a href="../xref/ch/qos/logback/classic/pattern/LoggerConverter.html">
<code>LoggerConverter</code></a>, the converter underlying the
%logger conversion word, extracts the name of the logger from
<code>ILoggingEvent</code> and returns it as a String. It might
abbreviate the logger name in the process.</p>
<p>Let us say that our customized <code>ClassicConverter</code>
colors the level of the logging event, according to ANSI terminal
conventions. Here is a possible implementation:</p>
<em> Example: Sample Converter Example
<a href="../xref/chapters/layouts/MySampleConverter.html">
(src/main/java/chapters/layouts/MySampleConverter.java)</a></em>
<pre class="prettyprint source">package chapters.layouts;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class MySampleConverter extends ClassicConverter {
private static final String END_COLOR = "\u001b[m";
private static final String ERROR_COLOR = "\u001b[0;31m";
private static final String WARN_COLOR = "\u001b[0;33m";
@Override
<b>public String convert(ILoggingEvent event) {
StringBuffer sbuf = new StringBuffer();
sbuf.append(getColor(event.getLevel()));
sbuf.append(event.getLevel());
sbuf.append(END_COLOR);
return sbuf.toString();
}</b>
/**
* Returns the appropriate characters to change the color for the specified
* logging level.
*/
private String getColor(Level level) {
switch (level.toInt()) {
case Level.ERROR_INT:
return ERROR_COLOR;
case Level.WARN_INT:
return WARN_COLOR;
default:
return "";
}
}
}
</pre>
<p>This implementation is relatively straightforward. The
<code>MySampleConverter</code> class extends
<code>ClassicConverter</code>, and implements the
<code>convert</code> method where it returns a level string
decorated with ANSI coloring codes.
</p>
<p>In the second step, we must let logback know about the new
<code>Converter</code>. For this purpose, we need to declare the
new conversion word in the configuration file, as shown below:</p>
<em> Example: Sample Converter Example (src/main/java/chapters/layouts/mySampleConverterConfig.xml)</em>
<span class="asGroovy" onclick="return asGroovy('mySampleConverterConfig');">View as .groovy</span>
<pre id="mySampleConverterConfig" class="prettyprint source"><configuration>
<b><conversionRule conversionWord="sample"
converterClass="chapters.layouts.MySampleConverter" /></b>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-4relative [%thread] <b>%sample</b> - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>Once the new conversion word has been declared in the
configuration file, we can refer to it within
<code>PatternLayout</code> pattern, as with any other
conversion word.</p>
<p>Given that ANSI terminal codes do not work on Windows, you can
view the results on non-Windows platforms such as Linux or
Mac. The following command:</p>
<div class="source">java chapters.layouts.SampleLogging src/main/java/chapters/layouts/mySampleConverterConfig.xml </div>
<p>should yield:</p>
<p class="source">0 [main] DEBUG - Everything's going well
3 [main] <span class="red">ERROR</span> - maybe not quite... </p>
<p>Please note that the string "ERROR" is highlighted in red,
which was the declared intent of the exercise.</p>
<p>The reader might want to take a look at other
<code>Converter</code> implementations such as
<a href="../xref/ch/qos/logback/classic/pattern/MDCConverter.html">
<code>MDCConverter</code></a> to learn about more complex
behaviours, such as option handling.
</p>
<h2>
<a name="ClassicHTMLLayout" href="#ClassicHTMLLayout">HTMLLayout</a>
</h2>
<p><a
href="../xref/ch/qos/logback/classic/html/HTMLLayout.html"><code>HTMLLayout</code></a>
(as included in logback-classic) generates logs in HTML
format. <code>HTMLLayout</code> outputs logging events in an HTML
table where each row of the table corresponds to a logging
event.</p>
<p>Here is a sample output produced by <code>HTMLLayout</code>
using its default CSS stylesheet:</p>
<img src="images/chapters/layouts/htmlLayout0.gif" alt="HTML Layout Sample Image"/>
<p>The content of table columns are specified with the help of a
conversion pattern. See <a
href="#ClassicPatternLayout"><code>PatternLayout</code></a> for
documentation on conversion patterns. As such, you have full
control over the contents and format of the table. You can select
and display any combination of converters
<code>PatternLayout</code> knows about.
</p>
<p>One notable exception about the use of
<code>PatternLayout</code> with <code>HTMLLayout</code> is that
conversion specifiers should not be separated by space characters
or more generally by literal text. Each specifier found in the
pattern will result in a separate column. Likewise a separate
column will be generated for each block of literal text found in
the pattern, potentially wasting valuable real-estate on your
screen.</p>
<p>Here is simple but functional configuration file illustrating
the use of <code>HTMLLayout</code>.
</p>
<em> Example: HTMLLayout Example (src/main/java/chapters/layouts/htmlLayoutConfig1.xml)</em>
<span class="asGroovy" onclick="return asGroovy('htmlLayoutConfig1');">View as .groovy</span>
<pre id="htmlLayoutConfig1" class="prettyprint source"><configuration debug="true">
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<b><pattern>%relative%thread%mdc%level%logger%msg</pattern></b>
</layout>
</encoder>
<file>test.html</file>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>
</pre>
<p>The <a
href="../xref/chapters/layouts/TrivialMain.html">TrivialMain</a>
application logs a few messages finishing with an exception. The
command:</p>
<p class="source">java chapters.layouts.TrivialMain src/main/java/chapters/layouts/htmlLayoutConfig1.xml</p>
<p>will create the file <em>test.html</em> in the current
folder. The contents of <em>test.html</em> should be similar to:
</p>
<img src="images/chapters/layouts/htmlLayout1.png" alt="HTML Layout Sample Image"/>
<h3>Stack traces</h3>
<p> If you use the <em>%em</em> conversion word to display stack
traces, a table column will be created to display stack traces. In
most cases the column will be empty, wasting screen
real-estate. Moreover, printing a stack trace on a separate column
does not yield very readable results. Fortunately, the
<em>%ex</em> conversion word is not the only way to display stack
traces.
</p>
<p>A better solution is available through implementations of
<code>IThrowableRenderer</code> interface. Such an implementation
can be assigned to <code>HTMLLayout</code> to manage the display
data related to exceptions. By default, a
<a href="../xref/ch/qos/logback/classic/html/DefaultThrowableRenderer.html">
<code>DefaultThrowableRenderer</code></a> is assigned to each
<code>HTMLLayout</code> instance. It writes exceptions on a
<em>new table row</em>, along with its stack trace, in an easily
readable manner, as shown on the figure above.
</p>
<p>If for some reason, you still wish to use the <em>%ex</em>
pattern, then you can specify <a
href="../xref/ch/qos/logback/core/html/NOPThrowableRenderer.html">
<code>NOPThrowableRenderer</code></a> in the configuration file in
order to disable displaying a separate row for the stack trace. We
don't have the faintest idea why you would want to do that, but if
you wished, you could.
</p>
<h3>CSS</h3>
<p>The presentation of the HTML created by <code>HTMLLayout</code>
is controlled through a Cascading Style Sheet (CSS). In the
absence of specific instructions, <code>HTMLLayout</code> will
default to its internal CSS. However, you can instruct
<code>HTMLLayout</code> to use an external CSS file. For this
purpose a <code>cssBuilder</code> element can be nested within a
<code><layout></code> element, as shown below.
</p>
<pre class="prettyprint source"><layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%relative...%msg</pattern>
<cssBuilder class="ch.qos.logback.classic.html.UrlCssBuilder">
<!-- url where the css file is located -->
<url>http://...</url>
</cssBuilder>
</layout></pre>
<p>The <code>HTMLLayout</code> is often used in conjunction with
<code>SMTPAppender</code> so that outgoing email is pleasantly
formatted in HTML.
</p>
<h2><a name="log4jXMLLayout" href="#log4jXMLLayout">Log4j
XMLLayout</a></h2>
<p><a
href="../xref/ch/qos/logback/classic/log4j/XMLLayout.html">XMLLayout</a>
(part of logback-classic) generates output in a log4j.dtd
compliant format to interoperate with tools such as <a
href="http://logging.apache.org/chainsaw/index.html">Chainsaw</a>
and <a href="http://vigilog.sourceforge.net/">Vigilog</a> capable
of processing files generated by <a
href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/XMLLayout.html">log4j's
XMLLayout</a>.
</p>
<p>As the original XMLLayout in log4j version 1.2.15, XMLLayout in
logback-classic takes two boolean properties, <span
class="option">locationInfo</span> and <span
class="option">properties</span>. Setting <span
class="option">locationInfo</span> to true enables the inclusion
of location info (caller data) in the each event. Setting <span
class="option">properties</span> to true enables the inclusion of
MDC information. Both options are set to false by default.
</p>
<p>Here is a sample configuration</p>
<em> Example: Log4jXMLLayout Example (src/main/java/chapters/layouts/log4jXMLLayout.xml)</em>
<span class="asGroovy" onclick="return asGroovy('log4jXMLLayout');">View as .groovy</span>
<pre id="log4jXMLLayout" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>test.xml</file>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.log4j.XMLLayout">
<locationInfo>true</locationInfo>
</layout>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration> </pre>
<h1><a name="logback-access" href="#logback-access">Logback access</a></h1>
<p>Most logback-access layouts are mere adaptations of
logback-classic layouts. Logback-classic and logback-access
modules address different needs, but in general offer comparable
functionality.</p>
<h2>Writing your own Layout</h2>
<p>Writing a custom <code>Layout</code> for logback access is
nearly identical to its sibling <code>Layout</code> in
logback-classic.</p>
<a name="AccessPatternLayout"></a>
<h3>PatternLayout</h3>
<p><a href="../xref/ch/qos/logback/access/PatternLayout.html">
<code>PatternLayout</code></a> in logback-access can be configured
in much the same way as its classic counterpart. However it
features additional conversion specifiers suited for logging
particular bits of information available only in HTTP servlet
requests and HTTP servlet responses.
</p>
<p>Below is a list of conversion specifiers for
<code>PatternLayout</code> in logback-access.</p>
<table class="bodyTable" border="0" cellpadding="8">
<tr>
<th align="center">Conversion Word</th>
<th align="center">Effect</th>
</tr>
<tr class="a">
<td align="center"><b>a / remoteIP</b></td>
<td>
<p>
Remote IP address.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>A / localIP</b></td>
<td>
<p>
Local IP address.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>b / B / byteSent</b></td>
<td>
<p>
Response's content length.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>h / clientHost</b></td>
<td>
<p>
Remote host.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>H / protocol</b></td>
<td>
<p>
Request protocol.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>l</b></td>
<td>
<p>
Remote log name. In logback-access, this converter always
returns the value "-".
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>reqParameter{paramName}</b></td>
<td>
<p>
Parameter of the response.
</p>
<p>This conversion word takes the first option in braces and looks
for the corresponding parameter in the request.</p>
<p><b>%reqParameter{input_data}</b>
displays the corresponding parameter.</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>i{header} / header{header}</b></td>
<td>
<p>
Request header.
</p>
<p>This conversion word takes the first option in braces and looks
for the corresponding header in the request.</p>
<p><b>%header{Referer}</b> displays the referer of the request.</p>
<p>
If no option is specified, it displays every available header.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>m / requestMethod</b></td>
<td>
<p>
Request method.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>r / requestURL</b></td>
<td>
<p>
URL requested.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>s / statusCode</b></td>
<td>
<p>
Status code of the request.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>t / date</b></td>
<td>
<p>Outputs the date of the logging event. The date
conversion specifier may be followed by a set of braces
containing a date and time pattern strings used by
<code>java.text.SimpleDateFormat</code>. <em>ABSOLUTE</em>,
<em>DATE</em> or <em>ISO8601</em> are also valid values.
</p>
<p>For example, <b>%d{HH:mm:ss,SSS}</b>,
<b>%d{dd MMM yyyy ;HH:mm:ss,SSS}</b> or
<b>%d{DATE}</b>. If no date format specifier is given then
ISO8601 format is assumed.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>u / user</b></td>
<td>
<p>
Remote user.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>U / requestURI</b></td>
<td>
<p>
Requested URI.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>v / server</b></td>
<td>
<p>Server name.</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>localPort</b></td>
<td>
<p>Local port.</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>reqAttribute{attributeName}</b></td>
<td>
<p>Attribute of the request.</p>
<p>This conversion word takes the first option in braces and looks
for the corresponding attribute in the request.</p>
<p><b>%reqAttribute{SOME_ATTRIBUTE}</b>
displays the corresponding attribute.</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>reqCookie{cookie}</b></td>
<td>
<p>Request cookie.</p>
<p>This conversion word takes the first option in braces and looks
for the corresponding cookie in the request.</p>
<p><b>%cookie{COOKIE_NAME}</b> displays corresponding cookie.</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>responseHeader{header}</b></td>
<td>
<p>
Header of the response.
</p>
<p>This conversion word takes the first option in braces and looks
for the corresponding header in the response.</p>
<p><b>%header{Referer}</b> displays the referer of the response.</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>requestContent</b></td>
<td>
<p>This conversion word displays the content of the request,
that is the request's <code>InputStream</code>. It is used
in conjunction with a <a
href="../xref/ch/qos/logback/access/servlet/TeeFilter.html">
<code>TeeFilter</code></a>, a
<code>javax.servlet.Filter</code> that replaces the original
<code>HttpServletRequest</code> by a <a
href="../xref/ch/qos/logback/access/servlet/TeeHttpServletRequest.html">
<code>TeeHttpServletRequest</code></a>. The latter object
allows access to the request's <code>InputStream</code>
multiple times without any loss of data.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>fullRequest</b></td>
<td>
<p>This converter outputs the data associated with the
request, including all headers and request contents.
</p>
</td>
</tr>
<tr class="b">
<td align="center"><b>responseContent</b></td>
<td>
<p>This conversion word displays the content of the
response, that is the response's
<code>InputStream</code>. It is used in conjunction with a
<a href="../xref/ch/qos/logback/access/servlet/TeeFilter.html">
<code>TeeFilter</code></a>, a
<code>javax.servlet.Filter</code> that replaces the original
<code>HttpServletResponse</code> by a <a
href="../xref/ch/qos/logback/access/servlet/TeeHttpServletResponse.html">
<code>TeeHttpServletResponse</code></a>. The latter object
allows access to the request's <code>InputStream</code>
multiple times without any loss of data.
</p>
</td>
</tr>
<tr class="a">
<td align="center"><b>fullResponse</b></td>
<td>
<p>This conversion word takes all the available data
associated with the response, including all headers of the
response and response contents.
</p>
</td>
</tr>
</table>
<p>Logback access' <code>PatternLayout</code> also recognizes three keywords, which
act like shortcuts to a certain pattern.</p>
<table class="bodyTable">
<tr>
<th>keyword</th>
<th>equivalent conversion pattern</th>
</tr>
<tr class="a">
<td><em>common</em> or <em>CLF</em></td>
<td><em>%h %l %u %t \"%r\" %s %b</em></td>
</tr>
<tr class="b">
<td><em>combined</em></td>
<td><em>%h %l %u %t \"%r\" %s %b \"%i{Referer}\" \"%i{User-Agent}\"</em></td>
</tr>
</table>
<p>The <em>common</em> keyword corresponds to the pattern <em>%h %l %u %t \"%r\" %s %b</em>
which displays client host, remote log name, user, date, requested URL, status code
and response's content length</p>
<p>The <em>combined</em> keyword is a shortcut for <em>%h %l %u %t
\"%r\" %s %b \"%i{Referer}\" \"%i{User-Agent}\"</em>. This pattern
begins much like the <em>common</em> pattern but also displays two
request headers, namely referer, and user-agent.</p>
<a name="AccessHTMLLayout"></a>
<h3>HTMLLayout</h3>
<p>The <a
href="../xref/ch/qos/logback/access/html/HTMLLayout.html"><code>HTMLLayout</code></a>
class found in logback-access is similar to the <a
href="#ClassicHTMLLayout"><code>HTMLLayout</code></a> class from
logback-classic.
</p>
<p>By default, it will create a table containing the following data:</p>
<ul>
<li>Remote IP</li>
<li>Date</li>
<li>Request URL</li>
<li>Status code</li>
<li>Content Length</li>
</ul>
<p>Here is a sample output produced by <code>HTMLLayout</code> in
logback-access:</p>
<img src="images/chapters/layouts/htmlLayoutAccess.gif" alt="Access HTML Layout Sample Image"/>
<p>What can be better than a real world example? Our own log4j
properties for logback <a
href="http://logback.qos.ch/translator/">translator</a> makes use
of logback-access to demonstrate live output from
<code>RollingFileAppender</code> with <code>HTMLLayout</code>.</p>
<p>On every new user request to our <a
href="http://logback.qos.ch/translator/">translator</a>
web-application, a new entry will be added to the access logs,
which you can view by <a
href="http://logback.qos.ch/translator/logs/access.html">following
this link</a>.</p>
<script src="../templates/footer.js" type="text/javascript"></script>
</div>
</body>
</html>
|