/usr/share/doc/liblogback-java/manual/appenders.html is in liblogback-java-doc 1:1.2.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 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 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 | <!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 4: Appenders</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 type="text/javascript" src="../templates/header.js"></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">
<h1>Chapter 4: Appenders</h1>
<a href="appenders_ja.html">和訳 (Japanese translation)</a>
<div class="quote">
<p><em>There is so much to tell about the Western country in
that day that it is hard to know where to start. One thing sets
off a hundred others. The problem is to decide which one to tell
first.</em></p>
<p>—JOHN STEINBECK, <em>East of Eden</em></p>
</div>
<script src="../templates/creative.js" type="text/javascript"></script>
<script src="../templates/setup.js" type="text/javascript"></script>
<h2 class="doAnchor" name="whatIsAnAppender">What is an Appender?</h2>
<p>Logback delegates the task of writing a logging event to
components called appenders. Appenders must implement the <a
href="../xref/ch/qos/logback/core/Appender.html"><code>ch.qos.logback.core.Appender</code></a>
interface. The salient methods of this interface are summarized
below:
</p>
<pre class="prettyprint source">package ch.qos.logback.core;
import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.FilterAttachable;
import ch.qos.logback.core.spi.LifeCycle;
public interface Appender<E> extends LifeCycle, ContextAware, FilterAttachable {
public String getName();
public void setName(String name);
<b>void doAppend(E event);</b>
}</pre>
<p>Most of the methods in the <code>Appender</code> interface are
setters and getters. A notable exception is the
<code>doAppend()</code> method taking an object instance of type
<em>E</em> as its only parameter. The actual type of <em>E</em>
will vary depending on the logback module. Within the
logback-classic module <em>E</em> would be of type <a
href="../apidocs/ch/qos/logback/classic/spi/ILoggingEvent.html">ILoggingEvent</a>
and within the logback-access module it would be of type <a
href="../apidocs/ch/qos/logback/access/spi/AccessEvent.html">AccessEvent</a>.
The <code>doAppend()</code> method is perhaps the most important in
the logback framework. It is responsible for outputting the logging
events in a suitable format to the appropriate output device.
</p>
<p>Appenders are named entities. This ensures that they can be
referenced by name, a quality confirmed to be instrumental in
configuration scripts. The <code>Appender</code> interface extends
the <code>FilterAttachable</code> interface. It follows that one or
more filters can be attached to an appender instance. Filters are
discussed in detail in a subsequent chapter.
</p>
<p>Appenders are ultimately responsible for outputting logging
events. However, they may delegate the actual formatting of the
event to a <code>Layout</code> or to an <code>Encoder</code> object.
Each layout/encoder is associated with one and only one appender,
referred to as the owning appender. Some appenders have a built-in
or fixed event format. Consequently, they do not require nor have a
layout/encoder. For example, the <code>SocketAppender</code> simply
serializes logging events before transmitting them over the wire.
</p>
<h2 class="doAnchor" name="AppenderBase">AppenderBase</h2>
<p>The <a href="../xref/ch/qos/logback/core/AppenderBase.html">
<code>ch.qos.logback.core.AppenderBase</code></a> class is an
abstract class implementing the <code>Appender</code> interface. It
provides basic functionality shared by all appenders, such as
methods for getting or setting their name, their activation status,
their layout and their filters. It is the super-class of all
appenders shipped with logback. Although an abstract class,
<code>AppenderBase</code> actually implements the
<code>doAppend()</code> method in the <code>Append</code> interface.
Perhaps the clearest way to discuss <code>AppenderBase</code> class
is by presenting an excerpt of actual source code.
</p>
<pre class="prettyprint source">public synchronized void doAppend(E eventObject) {
// prevent re-entry.
if (guard) {
return;
}
try {
guard = true;
if (!this.started) {
if (statusRepeatCount++ < ALLOWED_REPEATS) {
addStatus(new WarnStatus(
"Attempted to append to non started appender [" + name + "].",this));
}
return;
}
if (getFilterChainDecision(eventObject) == FilterReply.DENY) {
return;
}
// ok, we now invoke the derived class's implementation of append
this.append(eventObject);
} finally {
guard = false;
}
}</pre>
<p>This implementation of the <code>doAppend()</code> method is
synchronized. It follows that logging to the same appender from
different threads is safe. While a thread, say <em>T</em>, is
executing the <code>doAppend()</code> method, subsequent calls by
other threads are queued until <em>T</em> leaves the
<code>doAppend()</code> method, ensuring <em>T</em>'s exclusive
access to the appender.
</p>
<p>Since such synchronization is not always appropriate, logback
ships with <a
href="../xref/ch/qos/logback/core/UnsynchronizedAppenderBase.html"><code>ch.qos.logback.core.UnsynchronizedAppenderBase</code></a>
which is very similar to the <a
href="../xref/ch/qos/logback/core/AppenderBase.html"><code>AppenderBase</code></a>
class. For the sake of conciseness, we will be discussing
<code>UnsynchronizedAppenderBase</code> in the remainder of this document.
</p>
<p>The first thing the <code>doAppend()</code> method does is to
check whether the guard is set to true. If it is, it immediately
exits. If the guard is not set, it is set to true at the next
statement. The guard ensures that the <code>doAppend()</code> method
will not recursively call itself. Just imagine that a component,
called somewhere beyond the <code>append()</code> method, wants to
log something. Its call could be directed to the very same appender
that just called it resulting in an infinite loop and a stack
overflow.
</p>
<p>In the following statement we check whether the
<code>started</code> field is true. If it is not,
<code>doAppend()</code> will send a warning message and return. In
other words, once an appender is closed, it is impossible to write
to it. <code>Appender</code> objects implement the
<code>LifeCycle</code> interface, which implies that they implement
<code>start()</code>, <code>stop()</code> and
<code>isStarted()</code> methods. After setting all the properties of
an appender, Joran, logback's configuration framework, calls the
<code>start()</code> method to signal the appender to activate its
properties. Depending on its kind, an appender may fail to start if
certain properties are missing or because of interference between
various properties. For example, given that file creation depends on
truncation mode, <code>FileAppender</code> cannot act on the value
of its <code>File</code> option until the value of the Append option
is also known with certainty. The explicit activation step ensures
that an appender acts on its properties <em>after</em> their values
become known.
</p>
<p>If the appender could not be started or if it has been stopped, a
warning message will be issued through logback's internal status
management system. After several attempts, in order to avoid
flooding the internal status system with copies of the same warning
message, the <code>doAppend()</code> method will stop issuing these
warnings.
</p>
<p>The next <code>if</code> statement checks the result of the
attached filters. Depending on the decision resulting from the
filter chain, events can be denied or explicitly accepted. In
the absence of a decision by the filter chain, events are accepted
by default.
</p>
<p>The <code>doAppend()</code> method then invokes the derived
classes' implementation of the <code>append()</code> method. This
method does the actual work of appending the event to the
appropriate device.
</p>
<p>Finally, the guard is released so as to allow a subsequent
invocation of the <code>doAppend()</code> method.
</p>
<p>For the remainder of this manual, we reserve the term "option" or
alternatively "property" for any attribute that is inferred
dynamically using JavaBeans introspection through setter and getter
methods. </p>
<h1>Logback-core</h1>
<p>Logback-core lays the foundation upon which the other logback
modules are built. In general, the components in logback-core
require some, albeit minimal, customization. However, in the next
few sections, we describe several appenders which are ready for use
out of the box.
</p>
<h2 class="doAnchor"
name="OutputStreamAppender">OutputStreamAppender
</h2>
<p><a
href="../xref/ch/qos/logback/core/OutputStreamAppender.html"><code>OutputStreamAppender</code></a>
appends events to a <code>java.io.OutputStream</code>. This class
provides basic services that other appenders build upon. Users do
not usually instantiate <code>OutputStreamAppender</code> objects
directly, since in general the <code>java.io.OutputStream</code>
type cannot be conveniently mapped to a string, as there is no way
to specify the target <code>OutputStream</code> object in a
configuration script. Simply put, you cannot configure a
<code>OutputStreamAppender</code> from a configuration file.
However, this does not mean that <code>OutputStreamAppender</code>
lacks configurable properties. These properties are described next.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" name="osaEncoder">encoder</span></td>
<td><a
href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a></td>
<td>Determines the manner in which an event is written to the
underlying <code>OutputStreamAppender</code>. Encoders are
described in a <a href="encoders.html">dedicated chapter</a>.
</td>
</tr>
<tr>
<td><span class="prop" name="immediateFlush">immediateFlush</span></td>
<td><code>boolean</code></td>
<td>The default value for <span
class="option">immediateFlush</span> is 'true'. Immediate
flushing of the output stream ensures that logging events are
immediately written out and will not be lost in case your
application exits without properly closing appenders. On the
other hand, setting this property to 'false' is likely to
quadruple (your mileage may vary) logging throughput. Again, if
<span class="option">immediateFlush</span> is set to 'false' and
if appenders are not closed properly when your application exits,
then logging events not yet written to disk may be lost.
</td>
</tr>
</table>
<p>The <code>OutputStreamAppender</code> is the super-class of three other
appenders, namely <code>ConsoleAppender</code>,
<code>FileAppender</code> which in turn is the super class of
<code>RollingFileAppender</code>. The next figure illustrates the
class diagram for <code>OutputStreamAppender</code> and its subclasses.
</p>
<img src="images/chapters/appenders/appenderClassDiagram.jpg" alt="A UML diagram showing OutputStreamAppender and sub-classes"/>
<h2 class="doAnchor" name="ConsoleAppender">ConsoleAppender</h2>
<p>The <a href="../xref/ch/qos/logback/core/ConsoleAppender.html">
<code>ConsoleAppender</code></a>, as the name indicates, appends on
the console, or more precisely on <em>System.out</em> or
<em>System.err</em>, the former being the default
target. <code>ConsoleAppender</code> formats events with the help of
an encoder specified by the user. Encoders will be discussed in a
subsequent chapter. Both <em>System.out</em> and <em>System.err</em>
are of type <code>java.io.PrintStream</code>. Consequently, they
are wrapped inside an <code>OutputStreamWriter</code> which buffers
I/O operations.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="conApp">encoder</span></td>
<td>
<a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a>
</td>
<td>See <code>OutputStreamAppender</code> properties.</td>
</tr>
<tr>
<td><span class="prop" container="conApp">target</span></td>
<td><code>String</code></td>
<td>
One of the String values <em>System.out</em> or
<em>System.err</em>. The default target is <em>System.out</em>.
</td>
</tr>
<tr>
<td><span class="prop" container="conApp">withJansi</span></td>
<td><code>boolean</code></td>
<td>By the default <span class="prop">withJansi</span> property
is set to <code>false</code>. Setting <span
class="prop">withJansi</span> to <code>true</code> activates the
<a href="http://jansi.fusesource.org/">Jansi</a> library which
provides support for ANSI color codes on Windows machines. On a
Windows host, if this property is set to true, then you should
put "org.fusesource.jansi:jansi:1.9" on the class
path. Note that Unix-based operating systems such as Linux and
Mac OS X support ANSI color codes by default.
<p>Under the Eclipse IDE, you might want to try the <a
href="http://www.mihai-nita.net/eclipse/">ANSI in Eclipse
Console</a> plugin.
</p>
</td>
</tr>
</table>
<p>Here is a sample configuration that uses
<code>ConsoleAppender</code>.
</p>
<p class="example">Example: ConsoleAppender configuration
(logback-examples/src/main/resources/chapters/appenders/conf/logback-Console.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback_Console');">View as .groovy</span>
<pre id="logback_Console" class="prettyprint source"><configuration>
<b><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
</encoder>
</appender></b>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration></pre>
<p>After you have set your current path to the
<em>logback-examples</em> directory and <a href="../setup.html">set
up your class path</a>, you can give the above configuration file a
whirl by issuing the following command:
</p>
<p class="source">java <a
href="../xref/chapters/appenders/ConfigurationTester.html">chapters.appenders.ConfigurationTester</a> src/main/java/chapters/appenders/conf/logback-Console.xml</p>
<h2 class="doAnchor" name="FileAppender">FileAppender</h2>
<p>The <a
href="../xref/ch/qos/logback/core/FileAppender.html"><code>FileAppender</code></a>,
a subclass of <code>OutputStreamAppender</code>, appends log events into
a file. The target file is specified by the <span
class="prop">File</span> option. If the file already exists, it
is either appended to, or truncated depending on the value of the
<span class="prop">append</span> property.
</p>
<table class="bodyTable properties striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="fileApppender">append</span></td>
<td><code>boolean</code></td>
<td>If true, events are appended at the end of an existing
file. Otherwise, if <span class="prop">append</span> is false,
any existing file is truncated. The <span
class="option">append</span> option is set to true by default.
</td>
</tr>
<tr >
<td><span class="prop" container="fileApppender">encoder</span></td>
<td>
<a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a>
</td>
<td>See <code>OutputStreamAppender</code> properties.</td>
</tr>
<tr>
<td><span class="prop"
container="fileApppender">file</span></td>
<td><code>String</code></td>
<td>The name of the file to write to. If the file does not
exist, it is created. On the MS Windows platform users
frequently forget to escape back slashes. For example, the
value <em>c:\temp\test.log</em> is not likely to be interpreted
properly as <em>'\t'</em> is an escape sequence interpreted as
a single tab character <em>(\u0009)</em>. Correct values can
be specified as <em>c:/temp/test.log</em> or alternatively as
<em>c:\\temp\\test.log</em>. The <span
class="prop">File</span> option has no default value.
<p>If the parent directory of the file does not exist,
<code>FileAppender</code> will automatically create it,
including any necessary but nonexistent parent directories.
</p>
</td>
</tr>
<tr>
<td><span class="prop" name="prudent">prudent</span></td>
<td><code>boolean</code></td>
<td>In prudent mode, <code>FileAppender</code> will safely
write to the specified file, even in the presence of other
<code>FileAppender</code> instances running in different
JVMs, potentially running on different hosts. The default
value for prudent mode is <code>false</code>.
<p>Prudent mode can be used in conjunction with
<code>RollingFileAppender</code> although some <a
href="#prudentWithRolling">restrictions apply</a>.</p>
<p>Prudent mode implies that <span
class="prop">append</span> property is automatically set to
true.
</p>
<p>Prudent more relies on exclusive file locks. Experiments
show that file locks approximately triple (x3) the cost of
writing a logging event. On an "average" PC writing to a file
located on a <b>local</b> hard disk, when prudent mode is
off, it takes about 10 microseconds to write a single logging
event. When prudent mode is on, it takes approximately 30
microseconds to output a single logging event. This
translates to logging throughput of 100'000 events per second
when prudent mode is off and approximately 33'000 events per
second in prudent mode.
</p>
<p>Prudent mode effectively serializes I/O operations between
all JVMs writing to the same file. Thus, as the number of
JVMs competing to access a file increases so will the delay
incurred by each I/O operation. As long as the <em>total</em>
number of I/O operations is in the order of 20 log requests
per second, the impact on performance should be
negligible. Applications generating 100 or more I/O
operations per second can see an impact on performance and
should avoid using <span class="prop">prudent</span> mode.
</p>
<p><span class="label">Networked file locks</span> When the
log file is located on a networked file system, the cost of
prudent mode is even greater. Just as importantly, file locks
over a networked file system can be sometimes strongly biased
such that the process currently owning the lock immediately
re-obtains the lock upon its release. Thus, while one process
hogs the lock for the log file, other processes starve
waiting for the lock to the point of appearing deadlocked.
</p>
<p>The impact of prudent mode is highly dependent on network
speed as well as the OS implementation details. We provide an
very small application called <a
href="https://gist.github.com/2794241">FileLockSimulator</a>
which can help you simulate the behavior of prudent mode in
your environment.
</p>
</td>
</tr>
</table>
<p><span class="label notice">Immediate Flush</span> By default,
each log event is immediately flushed to the underlying output
stream. This default approach is safer in the sense that logging
events are not lost in case your application exits without properly
closing appenders. However, for significantly increased logging
throughput, you may want to set the <span
class="prop">immediateFlush</span> property to
<code>false</code>.</p>
<p>Below is an example of a configuration file for
<code>FileAppender</code>:
</p>
<p class="example">Example: FileAppender configuration
(logback-examples/src/main/resources/chapters/appenders/conf/logback-fileAppender.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-fileAppender');">View as .groovy</span>
<pre id="logback-fileAppender" class="prettyprint source"><configuration>
<b><appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>testFile.log</file>
<append>true</append>
<!-- set immediateFlush to false for much higher logging throughput -->
<immediateFlush>true</immediateFlush>
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender></b>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>After changing the current directory to
<em>logback-examples</em>, run this example by launching the
following command:
</p>
<p class="source">java chapters.appenders.ConfigurationTester
src/main/java/chapters/appenders/conf/logback-fileAppender.xml</p>
<h3 class="doAnchor" name="uniquelyNamed">Uniquely named files (by
timestamp)</h3>
<p>During the application development phase or in the case of
short-lived applications, e.g. batch applications, it is desirable
to create a new log file at each new application launch. This is
fairly easy to do with the help of the <code><timestamp></code>
element. Here's an example.</p>
<p class="example">Example: Uniquely named FileAppender
configuration by timestamp
(logback-examples/src/main/resources/chapters/appenders/conf/logback-timestamp.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-timestamp');">View as .groovy</span>
<pre id="logback-timestamp" class="prettyprint source"><configuration>
<!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under
the key "bySecond" into the logger context. This value will be
available to all subsequent configuration elements. -->
<b><timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/></b>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<!-- use the previously created timestamp to create a uniquely
named log file -->
<file><b>log-${bySecond}.txt</b></file>
<encoder>
<pattern>%logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>The timestamp element takes two mandatory attributes <span
class="attr">key</span> and <span class="attr">datePattern</span>
and an optional <span class="attr">timeReference</span>
attribute. The <span class="attr">key</span> attribute is the name
of the key under which the timestamp will be available to
subsequent configuration elements <a
href="configuration.html#variableSubstitution">as a
variable</a>. The <span class="attr">datePattern</span> attribute
denotes the date pattern used to convert the current time (at which
the configuration file is parsed) into a string. The date pattern
should follow the conventions defined in <a
href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>. The
<span class="attr">timeReference</span> attribute denotes the time
reference for the time stamp. The default is the
interpretation/parsing time of the configuration file, i.e. the
current time. However, under certain circumstances it might be
useful to use the context birth time as time reference. This can be
accomplished by setting the <span class="attr">timeReference</span>
attribute to <code>"contextBirth"</code>.
</p>
<p>Experiment with the <code><timestamp></code> element by
running the command:</p>
<p class="command">java chapters.appenders.ConfigurationTester src/main/resources/chapters/appenders/conf/logback-timestamp.xml</p>
<p>To use the logger context birth date as time reference, you
would set the <span class="attr">timeReference</span> attribute to
"contextBirth" as shown below.</p>
<p class="example">Example: Timestamp using context birth date as time reference
(logback-examples/src/main/resources/chapters/appenders/conf/logback-timestamp-contextBirth.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-timestamp-contextBirth');">View as .groovy</span>
<pre id="logback-timestamp-contextBirth" class="prettyprint source"><configuration>
<timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"
<b>timeReference="contextBirth"</b>/>
...
</configuration></pre>
<h2 class="doAnchor" name="RollingFileAppender">RollingFileAppender
</h2>
<p><a
href="../xref/ch/qos/logback/core/rolling/RollingFileAppender.html"><code>RollingFileAppender</code></a>
extends <code>FileAppender</code> with the capability to rollover log
files. For example, <code>RollingFileAppender</code> can log to a
file named <em>log.txt</em> file and, once a certain condition is
met, change its logging target to another file.
</p>
<p>There are two important sub-components that interact with
<code>RollingFileAppender</code>. The first
<code>RollingFileAppender</code> sub-component, namely
<code>RollingPolicy</code>, (<a href="#onRollingPolicies">see
below</a>) is responsible for undertaking the actions required for
a rollover. A second sub-component of
<code>RollingFileAppender</code>, namely
<code>TriggeringPolicy</code>, (<a href="#TriggeringPolicy">see
below</a>) will determine if and exactly when rollover
occurs. Thus, <code>RollingPolicy</code> is responsible for the
<em>what</em> and <code>TriggeringPolicy</code> is responsible for
the <em>when</em>. </p>
<p>To be of any use, a <code>RollingFileAppender</code> must have
both a <code>RollingPolicy</code> and a
<code>TriggeringPolicy</code> set up. However, if its
<code>RollingPolicy</code> also implements the
<code>TriggeringPolicy</code> interface, then only the former needs
to be specified explicitly.
</p>
<p>Here are the available properties for <code>RollingFileAppender</code>:</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="rfa">file</span></td>
<td><code>String</code></td>
<td>See <code>FileAppender</code> properties.</td>
</tr>
<tr>
<td><span class="prop" container="rfa">append</span></td>
<td><code>boolean</code></td>
<td>See <code>FileAppender</code> properties.</td>
</tr>
<tr>
<td><span class="prop" container="rfa">encoder</span></td>
<td>
<a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a>
</td>
<td>See <code>OutputStreamAppender</code> properties.</td>
</tr>
<tr>
<td><span class="prop" container="rfa">rollingPolicy</span></td>
<td><code>RollingPolicy</code></td>
<td>This option is the component that will dictate
<code>RollingFileAppender</code>'s behavior when rollover
occurs. See more information below.
</td>
</tr>
<tr>
<td><span class="prop" container="rfa">triggeringPolicy</span></td>
<td><code>TriggeringPolicy</code></td>
<td>
This option is the component that will tell
<code>RollingFileAppender</code> when to activate the rollover
procedure. See more information below.
</td>
</tr>
<tr>
<td valign="top"><span class="prop" name="prudentWithRolling">prudent</span></td>
<td valign="top"><code>boolean</code></td>
<td valign="top">
<a
href="#FixedWindowRollingPolicy"><code>FixedWindowRollingPolicy</code></a>
is not supported in prudent mode.
<p> <code>RollingFileAppender</code> supports the prudent
mode in conjunction with <a
href="#TimeBasedRollingPolicy"><code>TimeBasedRollingPolicy</code></a>
albeit with two restrictions.
</p>
<ol>
<li>In prudent mode, file compression is not supported nor
allowed. (We can't have one JVM writing to a file while
another JVM is compressing it.) </li>
<li>The <span class="prop">file</span> property of
<code>FileAppender</code> cannot be set and must be left
blank. Indeed, most operating systems do not allow renaming
of a file while another process has it opened.
</li>
</ol>
See also properties for <code>FileAppender</code>.
</td>
</tr>
</table>
<h3 class="doAnchor" name="onRollingPolicies">Overview of rolling
policies</h3>
<p><a
href="../xref/ch/qos/logback/core/rolling/RollingPolicy.html"><code>RollingPolicy</code></a>
is responsible for the rollover procedure which involves file
moving and renaming.</p>
<p>The <code>RollingPolicy</code> interface is presented below:</p>
<pre class="prettyprint source">package ch.qos.logback.core.rolling;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.spi.LifeCycle;
public interface RollingPolicy extends LifeCycle {
<b>public void rollover() throws RolloverFailure;</b>
public String getActiveFileName();
public CompressionMode getCompressionMode();
public void setParent(FileAppender appender);
}</pre>
<p>The <code>rollover</code> method accomplishes the work involved
in archiving the current log file. The
<code>getActiveFileName()</code> method is called to compute the
file name of the current log file (where live logs are written
to). As indicated by <code>getCompressionMode</code> method a
RollingPolicy is also responsible for determining the compression
mode. Lastly, a <code>RollingPolicy</code> is given a reference to
its parent via the <code>setParent</code> method.
</p>
<!-- =================
================= -->
<h4 class="doAnchor" name="TimeBasedRollingPolicy">TimeBasedRollingPolicy </h4>
<p><a
href="../xref/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.html">
<code>TimeBasedRollingPolicy</code></a> is possibly the most
popular rolling policy. It defines a rollover policy based on time,
for example by day or by month.
<code>TimeBasedRollingPolicy</code> assumes the responsibility for
rollover as well as for the triggering of said rollover. Indeed,
<code>TimeBasedTriggeringPolicy</code> implements <em>both</em>
<code>RollingPolicy</code> and <code>TriggeringPolicy</code>
interfaces.
</p>
<p><code>TimeBasedRollingPolicy</code>'s configuration takes one
mandatory <span class="prop">fileNamePattern</span> property and
several optional properties.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="tbrp">fileNamePattern</span></td>
<td><code>String</code></td>
<td>
The mandatory <span class="prop">fileNamePattern</span>
property defines the name of the rolled-over (archived) log
files. Its value should consist of the name of the file, plus
a suitably placed <em>%d</em> conversion specifier. The
<em>%d</em> conversion specifier may contain a date-and-time
pattern as specified by the
<code>java.text.SimpleDateFormat</code> class. If the
date-and-time pattern is omitted, then the default pattern
<em>yyyy-MM-dd</em> is assumed. <b>The rollover period is
inferred from the value of <span
class="prop">fileNamePattern</span>.</b>
<p>Note that the <span class="prop">file</span> property in
<code>RollingFileAppender</code> (the parent of
<code>TimeBasedRollingPolicy</code>) can be either set or
omitted. By setting the <span class="prop">file</span>
property of the containing <code>FileAppender</code>, you can
decouple the location of the active log file and the location
of the archived log files. The current logs will be always
targeted at the file specified by the <span
class="prop">file</span> property. It follows that the name
of the currently active log file will not change over
time. However, if you choose to omit the <span
class="prop">file</span> property, then the active file
will be computed anew for each period based on the value of
<span class="prop">fileNamePattern</span>. The examples
below should clarify this point.
</p>
<p>The date-and-time pattern, as found within the accolades
of %d{} follow java.text.SimpleDateFormat conventions. The
forward slash '/' or backward slash '\' characters anywhere
within the <span class="option">fileNamePattern</span>
property or within the date-and-time pattern will be
interpreted as directory separators.
</p>
<h5>Multiple %d specifiers</h5>
<p>It is possible to specify multiple %d specifiers but only
one of which can be primary, i.e. used to infer the rollover
period. All other tokens <em>must</em> be marked as auxiliary
by passing the 'aux' parameter (see examples below).</p>
<p>Multiple %d specifiers allow you to organize archive files
in a folder structure different than that of the roll-over
period. For example, the file name pattern shown below
organizes log folders by year and month but roll-over log
files every day at midnight.</p>
<pre>/var/log/<b>%d{yyyy/MM, aux}</b>/myapplication.<b>%d{yyyy-MM-dd}</b>.log</pre>
<h5>TimeZone</h5>
<p>Under certain circumstances, you might wish to roll-over
log files according to a clock in a timezone different than
that of the host. It is possible to pass a timezone argument
following the date-and-time pattern within the %d conversion
specifier. For example:</p>
<pre>aFolder/test.<b>%d</b>{yyyy-MM-dd-HH, <b>UTC</b>}.log</pre>
<p>If the specified timezone identifier is unknown or
misspelled, the GMT timezone is assumed as dictated by the <a
href="http://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone(java.lang.String)">TimeZone.getTimeZone(String)</a>
method specification.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="tbrp">maxHistory</span></td>
<td>int</td>
<td>The optional <span class="prop">maxHistory</span> property
controls the maximum number of archive files to keep,
asynchronously deleting older files. For example, if you
specify monthly rollover, and set maxHistory to 6, then 6
months worth of archives files will be kept with files older
than 6 months deleted. Note as old archived log files are
removed, any folders which were created for the purpose of log
file archiving will be removed as appropriate.
</td>
</tr>
<tr>
<td><span class="prop" container="tbrp">totalSizeCap</span></td>
<td>int</td>
<td><p>The optional <span class="prop">totalSizeCap</span>
property controls the total size of all archive files. Oldest
archives are deleted asynchronously when the total size cap is
exceeded. The <span class="prop">totalSizeCap</span> property
requires <span class="option">maxHistory</span> property to be
set as well. Moreover, the "max history" restriction is always
applied first and the "total size cap" restriction applied
second. </p>
</td>
</tr>
<tr >
<td><span class="prop"
container="tbrp">cleanHistoryOnStart</span></td>
<td>boolean</td>
<td>
<p>If set to true, archive removal will be executed on
appender start up. By default this property is set to
false. </p>
<p>Archive removal is normally performed during roll
over. However, some applications may not live long enough for
roll over to be triggered. It follows that for such
short-lived applications archive removal may never get a
chance to execute. By setting <span
class="prop">cleanHistoryOnStart</span> to true, archive
removal is performed at appender start up.</p>
</td>
</tr>
</table>
<p>Here are a few <code>fileNamePattern</code> values with an
explanation of their effects.</p>
<table class="bodyTable striped">
<tr>
<th>
<span class="prop">fileNamePattern</span>
</th>
<th>Rollover schedule</th>
<th>Example</th>
</tr>
<tr>
<td class="small">
<em>/wombat/foo.%d</em>
</td>
<td>Daily rollover (at midnight). Due to the omission of the
optional time and date pattern for the <em>%d</em> token
specifier, the default pattern of <em>yyyy-MM-dd</em> is
assumed, which corresponds to daily rollover.
</td>
<td>
<p><span class="prop">file</span> property not set: During November
23rd, 2006, logging output will go to the file
<em>/wombat/foo.2006-11-23</em>. At midnight and for the
rest of the 24th, logging output will be directed to
<em>/wombat/foo.2006-11-24</em>.
</p>
<p><span class="prop">file</span> property set to
<em>/wombat/foo.txt</em>: During November 23rd, 2006, logging
output will go to the file <em>/wombat/foo.txt</em>. At
midnight, <em>foo.txt</em> will be renamed as
<em>/wombat/foo.2006-11-23</em>. A new
<em>/wombat/foo.txt</em> file will be created and for the
rest of November 24th logging output will be directed to
<em>foo.txt</em>.
</p>
</td>
</tr>
<tr>
<td class="small">
<em>/wombat/%d{yyyy/MM}/foo.txt</em>
</td>
<td>Rollover at the beginning of each month.</td>
<td>
<p><span class="prop">file</span> property not set: During
the month of October 2006, logging output will go to
<em>/wombat/2006/10/foo.txt</em>. After midnight of October
31st and for the rest of November, logging output will be
directed to <em>/wombat/2006/11/foo.txt</em>.
</p>
<p><span class="prop">file</span> property set to
<em>/wombat/foo.txt</em>: The active log file will always be
<em>/wombat/foo.txt</em>. During the month of October 2006,
logging output will go to <em>/wombat/foo.txt</em>. At
midnight of October 31st, <em>/wombat/foo.txt</em> will be
renamed as <em>/wombat/2006/10/foo.txt</em>. A new
<em>/wombat/foo.txt</em> file will be created where logging
output will go for the rest of November. At midnight of
November 30th, <em>/wombat/foo.txt</em> will be renamed as
<em>/wombat/2006/11/foo.txt</em> and so on.
</p>
</td>
</tr>
<tr>
<td class="small">
<em>/wombat/foo.%d{yyyy-ww}.log</em>
</td>
<td>Rollover at the first day of each week. Note that the first
day of the week depends on the locale.</td>
<td>Similar to previous cases, except that rollover will occur
at the beginning of every new week.
</td>
</tr>
<tr>
<td class="small">
<em>/wombat/foo%d{yyyy-MM-dd_HH}.log</em>
</td>
<td>Rollover at the top of each hour.</td>
<td>Similar to previous cases, except that rollover will occur
at the top of every hour.
</td>
</tr>
<tr>
<td class="small">
<em>/wombat/foo%d{yyyy-MM-dd_HH-mm}.log</em>
</td>
<td>Rollover at the beginning of every minute.</td>
<td>Similar to previous cases, except that rollover will occur
at the beginning of every minute.
</td>
</tr>
<tr>
<td class="small">
<em>/wombat/foo%d{yyyy-MM-dd_HH-mm, UTC}.log</em>
</td>
<td>Rollover at the beginning of every minute.</td>
<td>Similar to previous cases, except that file names will be
expressed in UTC.
</td>
</tr>
<tr>
<td class="small">
<em>/foo/%d{yyyy-MM,<b>aux</b>}/%d.log</em>
</td>
<td>Rollover daily. Archives located under a folder containing
year and month.
</td>
<td>In this example, the first %d token is marked as
<b>aux</b>iliary. The second %d token, with time and date
pattern omitted, is then assumed to be primary. Thus, rollover
will occur daily (default for %d) and the folder name will
depend on the year and month. For example, during the month of
November 2006, archived files will all placed under the
/foo/2006-11/ folder, e.g <em>/foo/2006-11/2006-11-14.log</em>.
</td>
</tr>
</table>
<p>Any forward or backward slash characters are interpreted as
folder (directory) separators. Any required folder will be created
as necessary. You can thus easily place your log files in separate
folders.
</p>
<p><code>TimeBasedRollingPolicy</code> supports automatic file
compression. This feature is enabled if the value of the <span
class="prop">fileNamePattern</span> option ends with <em>.gz</em>
or <em>.zip</em>.
</p>
<table class="bodyTable striped">
<tr class="a">
<th><span class="prop">fileNamePattern</span></th>
<th>Rollover schedule</th>
<th>Example</th>
</tr>
<tr>
<td><em>/wombat/foo.%d.gz</em></td>
<td>Daily rollover (at midnight) with automatic GZIP compression of the
archived files.</td>
<td>
<p><span class="prop">file</span> property not set: During
November 23rd, 2009, logging output will go to the file
<em>/wombat/foo.2009-11-23</em>. However, at midnight that
file will be compressed to become
<em>/wombat/foo.2009-11-23.gz</em>. For the 24th of November,
logging output will be directed to
<em>/wombat/folder/foo.2009-11-24</em> until it's rolled over
at the beginning of the next day.
</p>
<p><span class="prop">file</span> property set to
/wombat/foo.txt: During November 23rd, 2009, logging output
will go to the file <em>/wombat/foo.txt</em>. At midnight that
file will be compressed and renamed as
<em>/wombat/foo.2009-11-23.gz</em>. A new
<em>/wombat/foo.txt</em> file will be created where logging
output will go for the rest of November 24rd. At midnight
November 24th, <em>/wombat/foo.txt</em> will be compressed and
renamed as <em>/wombat/foo.2009-11-24.gz</em> and so on.
</p>
</td>
</tr>
</table>
<p>The <span class="prop">fileNamePattern</span> serves a dual
purpose. First, by studying the pattern, logback computes the
requested rollover periodicity. Second, it computes each archived
file's name. Note that it is possible for two different patterns to
specify the same periodicity. The patterns <em>yyyy-MM</em> and
<em>yyyy@MM</em> both specify monthly rollover, although the
resulting archive files will carry different names.
</p>
<p>By setting the <span class="prop">file</span> property you can
decouple the location of the active log file and the location of
the archived log files. The logging output will be targeted into
the file specified by the <span class="prop">file</span>
property. It follows that the name of the active log file will not
change over time. However, if you choose to omit the <span
class="prop">file</span> property, then the active file will be
computed anew for each period based on the value of <span
class="prop">fileNamePattern</span>. By leaving the <span
class="prop">file</span> option unset you can avoid file <a
href="../codes.html#renamingError">renaming errors</a> which occur
while there exist external file handles referencing log files during
roll over.
</p>
<p>The <span class="prop">maxHistory</span> property controls the
maximum number of archive files to keep, deleting older files. For
example, if you specify monthly rollover, and set <span
class="prop">maxHistory</span> to 6, then 6 months worth of
archives files will be kept with files older than 6 months
deleted. Note as old archived log files are removed, any folders
which were created for the purpose of log file archiving will be
removed as appropriate.
</p>
<p>For various technical reasons, rollovers are not clock-driven
but depend on the arrival of logging events. For example, on 8th of
March 2002, assuming the <span
class="prop">fileNamePattern</span> is set to <em>yyyy-MM-dd</em>
(daily rollover), the arrival of the first event after midnight
will trigger a rollover. If there are no logging events during, say
23 minutes and 47 seconds after midnight, then rollover will
actually occur at 00:23'47 AM on March 9th and not at 0:00 AM.
Thus, depending on the arrival rate of events, rollovers might be
triggered with some latency. However, regardless of the delay, the
rollover algorithm is known to be correct, in the sense that all
logging events generated during a certain period will be output in
the correct file delimiting that period.
</p>
<p>Here is a sample configuration for
<code>RollingFileAppender</code> in conjunction with a
<code>TimeBasedRollingPolicy</code>.
</p>
<p class="example">Example: Sample configuration of a
<code>RollingFileAppender</code> using a
<code>TimeBasedRollingPolicy</code>
(logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingTimeBased.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-RollingTimeBased');">View as .groovy</span>
<pre id="logback-RollingTimeBased" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logFile.log</file>
<b><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- keep 30 days' worth of history capped at 3GB total size -->
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy></b>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<p>The next configuration sample illustrates the use of
<code>RollingFileAppender</code> associated with
<code>TimeBasedRollingPolicy</code> in <span class="prop">prudent</span>
mode.
</p>
<p class="example">Example: Sample configuration of a
<code>RollingFileAppender</code> using a
<code>TimeBasedRollingPolicy</code>
(logback-examples/src/main/resources/chapters/appenders/conf/logback-PrudentTimeBasedRolling.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-PrudentTimeBasedRolling');">View as .groovy</span>
<pre id="logback-PrudentTimeBasedRolling" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<b><!-- Support multiple-JVM writing to the same log file --></b>
<b><prudent>true</prudent></b>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<h3 class="doAnchor" name="SizeAndTimeBasedRollingPolicy">Size and
time based rolling policy</h3>
<p>Sometimes you may wish to archive files essentially by date but
at the same time limit the size of each log file, in particular if
post-processing tools impose size limits on the log files. In
order to address this requirement, logback ships with
<code>SizeAndTimeBasedRollingPolicy</code>.</p>
<p>Note that <code>TimeBasedRollingPolicy</code> already allows
limiting the combined size of archived log files. If you only wish
to limit the combined size of log archives, then
<code>TimeBasedRollingPolicy</code> described above and setting
the <a href="#tbrpTotalSizeCap"><span
class="option">totalSizeCap</span></a> property should be amply
sufficent.
</p>
<p>Here is a sample configuration file demonstrating time and size
based log file archiving.</p>
<p class="example">Example: Sample configuration for
<code>SizeAndTimeBasedFNATP</code>
(logback-examples/src/main/resources/chapters/appenders/conf/logback-sizeAndTime.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-sizeAndTime');">View as .groovy</span>
<pre id="logback-sizeAndTime" class="prettyprint source"><configuration>
<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>mylog.txt</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern><b>mylog-%d{yyyy-MM-dd}.<span class="big">%i</span>.txt</b></fileNamePattern>
<b><!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB --></b>
<b><maxFileSize>100MB</maxFileSize></b>
<maxHistory>60</maxHistory>
<totalSizeCap>20GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="ROLLING" />
</root>
</configuration></pre>
<p>Note the "%i" conversion token in addition to "%d". <b>Both the
%i and %d tokens are mandatory.</b> Each time the current log file
reaches <span class="prop">maxFileSize</span> before the current
time period ends, it will be archived with an increasing index,
starting at 0.</p>
<p>Size and time based archiving supports deletion of old archive
files. You need to specify the number of periods to preserve with
the <span class="prop">maxHistory</span> property. When your
application is stopped and restarted, logging will continue at the
correct location, i.e. at the largest index number for the current
period.
</p>
<p>In versions prior to 1.1.7, this document mentioned a component
called <code>SizeAndTimeBasedFNATP</code>. However, given that
<code>SizeAndTimeBasedFNATP</code> offers a simpler configuration
structure, we no longer document
<code>SizeAndTimeBasedFNATP</code>. Nevertheless, earlier
configuration files using <code>SizeAndTimeBasedFNATP</code> will
continue to work just fine. In fact,
<code>SizeAndTimeBasedRollingPolicy</code> is implemented with a
<code>SizeAndTimeBasedFNATP</code> subcomponent.</p>
<h4 class="doAnchor" name="FixedWindowRollingPolicy">FixedWindowRollingPolicy</h4>
<p>When rolling over, <a
href="../xref/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.html">
<code>FixedWindowRollingPolicy</code></a> renames files according
to a fixed window algorithm as described below.
</p>
<p>The <span class="prop">fileNamePattern</span> option
represents the file name pattern for the archived (rolled over) log
files. This option is required and must include an integer token
<em>%i</em> somewhere within the pattern.
</p>
<p>Here are the available properties for
<code>FixedWindowRollingPolicy</code>
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="fwrp">minIndex</span></td>
<td><code>int</code></td>
<td>
<p>This option represents the lower bound for the window's
index.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="fwrp">maxIndex</span></td>
<td><code>int</code></td>
<td>
<p>This option represents the upper bound for the window's
index.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="fwrp">fileNamePattern</span></td>
<td><code>String</code></td>
<td>
<p>This option represents the pattern that will be followed
by the <code>FixedWindowRollingPolicy</code> when renaming
the log files. It must contain the string <em>%i</em>, which
will indicate the position where the value of the current
window index will be inserted.
</p>
<p>For example, using <em>MyLogFile%i.log</em> associated
with minimum and maximum values of <em>1</em> and <em>3</em>
will produce archive files named <em>MyLogFile1.log</em>,
<em>MyLogFile2.log</em> and <em>MyLogFile3.log</em>.
</p>
<p>Note that file compression is also specified via this
property. For example, <span
class="prop">fileNamePattern</span> set to
<em>MyLogFile%i.log.zip</em> means that archived files must be
compressed using the <em>zip</em> format; <em>gz</em> format
is also supported.
</p>
</td>
</tr>
</table>
<p>Given that the fixed window rolling policy requires as many file
renaming operations as the window size, large window sizes are
strongly discouraged. When large values are specified by the user,
the current implementation will automatically reduce the window
size to 20.
</p>
<p>Let us go over a more concrete example of the fixed window
rollover policy. Suppose that <span class="prop">minIndex</span> is
set to <em>1</em>, <span class="prop">maxIndex</span> set to
<em>3</em>, <span class="prop">fileNamePattern</span> property set
to <em>foo%i.log</em>, and that <span class="prop">file</span>
property is set to <em>foo.log</em>.
</p>
<table class="bodyTable striped">
<tr>
<th>Number of rollovers</th>
<th>Active output target</th>
<th>Archived log files</th>
<th>Description</th>
</tr>
<tr>
<td>0</td>
<td>foo.log</td>
<td>-</td>
<td>No rollover has happened yet, logback logs into the initial
file.
</td>
</tr>
<tr>
<td>1</td>
<td>foo.log</td>
<td>foo1.log</td>
<td>First rollover. <em>foo.log</em> is renamed as
<em>foo1.log</em>. A new <em>foo.log</em> file is created and
becomes the active output target.
</td>
</tr>
<tr>
<td>2</td>
<td>foo.log</td>
<td>foo1.log, foo2.log</td>
<td>Second rollover. <em>foo1.log</em> is renamed as
<em>foo2.log</em>. <em>foo.log</em> is renamed as
<em>foo1.log</em>. A new <em>foo.log</em> file is created and
becomes the active output target.
</td>
</tr>
<tr>
<td>3</td>
<td>foo.log</td>
<td>foo1.log, foo2.log, foo3.log</td>
<td>Third rollover. <em>foo2.log</em> is renamed as
<em>foo3.log</em>. <em>foo1.log</em> is renamed as
<em>foo2.log</em>. <em>foo.log</em> is renamed as
<em>foo1.log</em>. A new <em>foo.log</em> file is created and
becomes the active output target.
</td>
</tr>
<tr>
<td>4</td>
<td>foo.log</td>
<td>foo1.log, foo2.log, foo3.log</td>
<td>In this and subsequent rounds, the rollover begins by
deleting <em>foo3.log</em>. Other files are renamed by
incrementing their index as shown in previous steps. In this and
subsequent rollovers, there will be three archive logs and one
active log file.
</td>
</tr>
</table>
<p>The configuration file below gives an example of configuring
<code>RollingFileAppender</code> and
<code>FixedWindowRollingPolicy</code>. Note that the <span
class="prop">File</span> option is mandatory even if it contains
some of the same information as conveyed with the <span
class="prop">fileNamePattern</span> option.
</p>
<p class="example">Example: Sample configuration of a <code>RollingFileAppender</code> using a
<code>FixedWindowRollingPolicy</code> (logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingFixedWindow.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-RollingFixedWindow');">View as .groovy</span>
<pre id="logback-RollingFixedWindow" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<b><file>test.log</file></b>
<b><rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>tests.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>3</maxIndex>
</rollingPolicy></b>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<h2>
<a name="TriggeringPolicy" href="#TriggeringPolicy">Overview of
triggering policies</a>
</h2>
<p><a
href="../xref/ch/qos/logback/core/rolling/TriggeringPolicy.html"><code>TriggeringPolicy</code></a>
implementations are responsible for instructing the
<code>RollingFileAppender</code> when to rollover.</p>
<p>The <code>TriggeringPolicy</code> interface contains only one
method.</p>
<pre class="prettyprint source">package ch.qos.logback.core.rolling;
import java.io.File;
import ch.qos.logback.core.spi.LifeCycle;
public interface TriggeringPolicy<E> extends LifeCycle {
<b>public boolean isTriggeringEvent(final File activeFile, final <E> event);</b>
}</pre>
<p>The <code>isTriggeringEvent()</code> method takes as parameters
the active file and the logging event currently being
processed. The concrete implementation determines whether the
rollover should occur or not, based on these parameters.
</p>
<p>The most widely-used triggering policy, namely
<code>TimeBasedRollingPolicy</code> which also doubles as a
rolling policy, was already <a
href="#TimeBasedRollingPolicy">discussed earlier</a> along with
other rolling policies. </p>
<h4><a name="SizeBasedTriggeringPolicy"
href="#SizeBasedTriggeringPolicy">SizeBasedTriggeringPolicy</a></h4>
<p><a
href="../xref/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.html">
<code>SizeBasedTriggeringPolicy</code></a> looks at the size of the
currently active file. If it grows larger than the specified size,
it will signal the owning <code>RollingFileAppender</code> to
trigger the rollover of the existing active file.
</p>
<p><code>SizeBasedTriggeringPolicy</code> accepts only one
parameter, namely <span class="prop">maxFileSize</span>, with a
default value of 10 MB.
</p>
<p>The <span class="prop">maxFileSize</span> option can be
specified in bytes, kilobytes, megabytes or gigabytes by suffixing
a numeric value with <em>KB</em>, <em>MB</em> and respectively
<em>GB</em>. For example, <em>5000000</em>, <em>5000KB</em>,
<em>5MB</em> and <em>2GB</em> are all valid values, with the first
three being equivalent.
</p>
<p>Here is a sample configuration with a
<code>RollingFileAppender</code> in conjunction with
<code>SizeBasedTriggeringPolicy</code> triggering rollover when
the log file reaches 5MB in size.
</p>
<p class="example">Example: Sample configuration of a
<code>RollingFileAppender</code> using a
<code>SizeBasedTriggeringPolicy</code>
(logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingSizeBased.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-RollingSizeBased');">View as .groovy</span>
<pre id="logback-RollingSizeBased" class="prettyprint source"><configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>test.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>test.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>3</maxIndex>
</rollingPolicy>
<b><triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy></b>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration></pre>
<!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx -->
<a name="Classic"></a>
<h2>Logback Classic</h2>
<p>While logging events are generic in logback-core, within
logback-classic they are always instances of
<code>ILoggingEvent</code>. Logback-classic is nothing more than a
specialized processing pipeline handling instances of
<code>ILoggingEvent</code>.
</p>
<h3 class="doAnchor" name="SocketAppender">SocketAppender and
SSLSocketAppender
</h3>
<p>The appenders covered thus far are only able to log to local
resources. In contrast, the <a
href="../xref/ch/qos/logback/classic/net/SocketAppender.html">
<code>SocketAppender</code></a> is designed to log to a remote
entity by transmitting serialized <code>ILoggingEvent</code>
instances over the wire. When using <code>SocketAppender</code>
logging events on the wire are sent in the clear. However, when
using <a href="../xref/ch/qos/logback/classic/net/SSLSocketAppender.html">
<code>SSLSocketAppender</code></a>, logging events are delivered over
a secure channel.</p>
<p>
The actual type of the serialized event
is <a
href="../xref/ch/qos/logback/classic/spi/LoggingEventVO.html"><code>LoggingEventVO</code></a>
which implements the <code>ILoggingEvent</code>
interface. Nevertheless, remote logging is non-intrusive as far as
the logging event is concerned. On the receiving end after
deserialization, the event can be logged as if it were generated
locally. Multiple <code>SocketAppender</code> instances running on
different machines can direct their logging output to a central
log server whose format is fixed. <code>SocketAppender</code>
does not take an associated layout because it sends serialized
events to a remote server. <code>SocketAppender</code> operates
above the <em>Transmission Control Protocol (TCP)</em> layer which
provides a reliable, sequenced, flow-controlled end-to-end octet
stream. Consequently, if the remote server is reachable, then log
events will eventually arrive there. Otherwise, if the remote
server is down or unreachable, the logging events will simply be
dropped. If and when the server comes back up, then event
transmission will be resumed transparently. This transparent
reconnection is performed by a connector thread which periodically
attempts to connect to the server.
</p>
<p>Logging events are automatically buffered by the native TCP
implementation. This means that if the link to server is slow but
still faster than the rate of event production by the client, the
client will not be affected by the slow network
connection. However, if the network connection is slower than the
rate of event production, then the client can only progress at the
network rate. In particular, in the extreme case where the network
link to the server is down, the client will be eventually blocked.
Alternatively, if the network link is up, but the server is down,
the client will not be blocked, although the log events will be
lost due to server unavailability.
</p>
<p>Even if a <code>SocketAppender</code> is no longer attached to
any logger, it will not be garbage collected in the presence of a
connector thread. A connector thread exists only if the
connection to the server is down. To avoid this garbage
collection problem, you should close the
<code>SocketAppender</code> explicitly. Long lived applications
which create/destroy many <code>SocketAppender</code> instances
should be aware of this garbage collection problem. Most other
applications can safely ignore it. If the JVM hosting the
<code>SocketAppender</code> exits before the
<code>SocketAppender</code> is closed, either explicitly or
subsequent to garbage collection, then there might be
untransmitted data in the pipe which may be lost. This is a common
problem on Windows based systems. To avoid lost data, it is
usually sufficient to <code>close()</code> the
<code>SocketAppender</code> either explicitly or by calling the
<code>LoggerContext</code>'s <code>stop()</code>
method before exiting the application.
</p>
<p>The remote server is identified by the <span
class="prop">remoteHost</span> and <span
class="prop">port</span> properties.
<code>SocketAppender</code> properties are listed in the following
table. <code>SSLSocketAppender</code> supports many additional
configuration properties, which are detailed in the section
entitled <a href="usingSSL.html">Using SSL</a>.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="socket">includeCallerData</span></td>
<td><code>boolean</code></td>
<td>
<p>
The <span class="prop" container="socket">includeCallerData</span> option takes a boolean value.
If true, the caller data will be available to the remote host.
By default no caller data is sent to the server.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="socket">port</span></td>
<td><code>int</code></td>
<td>
<p>
The port number of the remote server.
</p>
</td>
</tr>
<tr>
<td><span class="prop"
container="socket">reconnectionDelay</span></td>
<td><code><a
href="../apidocs/ch/qos/logback/core/util/Duration.html">Duration</a></code></td>
<td>
The <span class="prop">reconnectionDelay</span> option takes
a duration string, such "10 seconds" representing the time
to wait between each failed connection attempt to the
server. The default value of this option is 30 seconds.
Setting this option to zero turns off reconnection
capability. Note that in case of successful connection to
the server, there will be no connector thread present.
</td>
</tr>
<tr>
<td><span class="prop" container="socket">queueSize</span></td>
<td><code>int</code></td>
<td>
<p>The <span class="prop">queueSize</span> property takes an
integer (greater than zero) representing the number of logging
events to retain for delivery to the remote receiver. When
the queue size is one, event delivery to the remote
receiver is synchronous. When the queue size is greater
than one, new events are enqueued, assuming that there is
space available in the queue. Using a queue length greater
than one can improve performance by eliminating delays caused
by transient network delays.
</p>
<p>See also the <span class="prop">eventDelayLimit</span>
property.</p>
</td>
</tr>
<tr>
<td><span class="prop" container="socket">eventDelayLimit</span></td>
<td><code><a
href="../apidocs/ch/qos/logback/core/util/Duration.html">Duration</a></code></td>
<td>
The <span class="prop">eventDelayLimit</span> option takes a
duration string, such "10 seconds". It represents the time
to wait before dropping events in case the local queue is
full, i.e. already contains <span
class="prop">queueSize</span> events. This may occur if the
remote host is persistently slow accepting events. The
default value of this option is 100 milliseconds.
</td>
</tr>
<tr>
<td><span class="prop" container="socket">remoteHost</span></td>
<td><code>String</code></td>
<td>
The host name of the server.
</td>
</tr>
<tr>
<td><span class="prop" container="socket">ssl</span></td>
<td><code>SSLConfiguration</code></td>
<td>Supported only for <code>SSLSocketAppender</code>, this
property provides the SSL configuration that will be used by
the appender, as described in <a href="usingSSL.html">Using SSL</a>.
</td>
</tr>
</table>
<h4>Logging Server Options</h4>
<p>The standard Logback Classic distribution includes two options
for servers that can be used to receive logging events from
<code>SocketAppender</code> or <code>SSLSocketAppender</code>.</p>
<ul>
<li><code>ServerSocketReceiver</code> and its SSL-enabled
counterpart <code>SSLServerSocketReceiver</code> are receiver
components which can be configured in the <em>logback.xml</em>
configuration file of an application in order receive events
from a remote socket appender. See <a href="receivers.html">
Receivers</a> for configuration details and usage examples.
</li>
<li><code>SimpleSocketServer</code> and its SSL-enabled counterpart
<code>SimpleSSLSocketServer</code> both offer an
easy-to-use standalone Java application that is designed to
be configured and run from your shell's command line interface.
These applications simply wait for logging events from
<code>SocketAppender</code> or <code>SSLSocketAppender</code>
clients. Each received event is logged according to local server
policy. Usage examples are given below.
</li>
</ul>
<h4><a name="simpleSocketServer"></a>Using SimpleSocketServer</h4>
<p>
The <code>SimpleSocketServer</code> application takes two command-line
arguments: <em>port</em> and <em>configFile</em>;
where <em>port</em> is the port to listen on and
<em>configFile</em> is a configuration script in XML format.
</p>
<p>
Assuming you are in the <em>logback-examples/</em> directory,
start <code>SimpleSocketServer</code> with the following command:
</p>
<p class="source">java ch.qos.logback.classic.net.SimpleSocketServer 6000 \
src/main/java/chapters/appenders/socket/server1.xml</p>
<p>where 6000 is the port number to listen on and
<em>server1.xml</em> is a configuration script that adds a
<code>ConsoleAppender</code> and a
<code>RollingFileAppender</code> to the root logger. After you
have started <code>SimpleSocketServer</code>, you can send it log
events from multiple clients using <code>SocketAppender</code>.
The examples associated with this manual include two such clients:
<code>chapters.appenders.SocketClient1</code> and
<code>chapters.appenders.SocketClient2</code> Both clients wait for the user
to type a line of text on the console. The text is encapsulated
in a logging event of level debug and then sent to the remote
server. The two clients differ in the configuration of the
<code>SocketAppender</code>. <code>SocketClient1</code> configures
the appender programmatically while <code>SocketClient2</code>
requires a configuration file.
</p>
<p>Assuming <code>SimpleSocketServer</code> is running on the
local host, you connect to it with the following command:
</p>
<p class="source">java chapters.appenders.socket.SocketClient1 localhost 6000</p>
<p>Each line that you type should appear on the console of the
<code>SimpleSocketServer</code> launched in the previous step. If
you stop and restart the <code>SimpleSocketServer</code> the
client will transparently reconnect to the new server instance,
although the events generated while disconnected will be simply
(and irrevocably) lost.
</p>
<p>
Unlike
<code>SocketClient1</code>, the sample application
<code>SocketClient2</code> does not configure logback by itself.
It requires a configuration file in XML format.
The configuration file <em>client1.xml</em>
shown below creates a <code>SocketAppender</code>
and attaches it to the root logger.
</p>
<p class="example">Example: SocketAppender configuration
(logback-examples/src/main/resources/chapters/appenders/socket/client1.xml)</p>
<span class="asGroovy" onclick="return asGroovy('client1');">View as .groovy</span>
<pre id="client1" class="prettyprint source"><configuration>
<appender name="SOCKET" class="ch.qos.logback.classic.net.SocketAppender">
<remoteHost>${host}</remoteHost>
<port>${port}</port>
<reconnectionDelay>10000</reconnectionDelay>
<includeCallerData>${includeCallerData}</includeCallerData>
</appender>
<root level="DEBUG">
<appender-ref ref="SOCKET" />
</root>
</configuration></pre>
<p>
Note that in the above configuration scripts the values for the
<span class="prop">remoteHost</span>, <span class="prop">port</span> and
<span class="prop">includeCallerData</span> properties
are not given directly but as substituted variable keys. The values for the variables
can be specified as system properties:
</p>
<p class="source">java -Dhost=localhost -Dport=6000 -DincludeCallerData=false \
chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/client1.xml</p>
<p>This command should give similar results to the previous
<code>SocketClient1</code>
example.
</p>
<p>Allow us to repeat for emphasis that serialization of logging
events is not intrusive. A deserialized event carries the same
information as any other logging event. It can be manipulated as
if it were generated locally; except that serialized logging
events by default do not include caller data. Here is an example
to illustrate the point. First, start
<code>SimpleSocketServer</code> with the following command:
</p>
<p class="source"> java ch.qos.logback.classic.net.SimpleSocketServer 6000 \
src/main/java/chapters/appenders/socket/server2.xml</p>
<p>The configuration file <em>server2.xml</em> creates a
<code>ConsoleAppender</code> whose layout outputs the caller's file
name and line number along with other information. If you run
<code>SocketClient2</code> with the configuration file
<em>client1.xml</em> as previously, you will notice that the output
on the server side will contain two question marks between
parentheses instead of the file name and the line number of the
caller:
</p>
<p class="source">2006-11-06 17:37:30,968 DEBUG [Thread-0] [?:?] chapters.appenders.socket.SocketClient2 - Hi</p>
<p>The outcome can be easily changed by instructing the
<code>SocketAppender</code> to include caller data by setting the
<span class="prop">includeCallerData</span> option to
true. Using the following command will do the trick:
</p>
<pre class="source">java -Dhost=localhost -Dport=6000 -DincludeCallerData=true \
chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/client1.xml</pre>
<p>As deserialized events can be handled in the same way as
locally generated events, they even can be sent to a second server
for further treatment. As an exercise, you may wish to setup two
servers where the first server tunnels the events it receives from
its clients to a second server.
</p>
<h4><a name="simpleSSLSocketServer"></a>Using SimpleSSLSocketServer</h4>
<p>The <code>SimpleSSLSocketServer</code> requires the same
<em>port</em> and <em>configFile</em> command-line arguments used
by <code>SimpleSocketServer</code>. Additionally, you must provide
the location and password for your logging server's X.509 credential
using system properties specified on the command line.
</p>
<p>Assuming you are in the <em>logback-examples/</em> directory,
start <code>SimpleSSLSocketServer</code> with the following command:
</p>
<p class="source">java -Djavax.net.ssl.keyStore=src/main/java/chapters/appenders/socket/ssl/keystore.jks \
-Djavax.net.ssl.keyStorePassword=changeit \
ch.qos.logback.classic.net.SimpleSSLSocketServer 6000 \
src/main/java/chapters/appenders/socket/ssl/server.xml
</p>
<p>This example runs <code>SimpleSSLSocketServer</code> using an
X.509 credential that is suitable for testing and experimentation,
only. <strong>Before using <code>SimpleSSLSocketServer</code> in a
production setting you should obtain an appropriate X.509 credential
to identify your logging server</strong>. See
<a href="usingSSL.html">Using SSL</a> for more details.
</p>
<p>Because the server configuration has <code>debug="true"</code>
specified on the root element, you'll will see in the server's
startup logging the SSL configuration that will be used. This is
useful in validating that local security policies are properly
implemented.
</p>
<p>With <code>SimpleSSLSocketServer</code> running, you can connect
to the server using an <code>SSLSocketAppender</code>. The following
example shows the appender configuration needed:
</p>
<p class="example">Example: SSLSocketAppender configuration
(logback-examples/src/main/resources/chapters/appenders/socket/ssl/client.xml)</p>
<span class="asGroovy" onclick="return asGroovy('sslclient');">View as .groovy</span>
<pre id="sslclient" class="prettyprint source"><configuration debug="true">
<appender name="SOCKET" class="ch.qos.logback.classic.net.SSLSocketAppender">
<remoteHost>${host}</remoteHost>
<port>${port}</port>
<reconnectionDelay>10000</reconnectionDelay>
<ssl>
<trustStore>
<location>${truststore}</location>
<password>${password}</password>
</trustStore>
</ssl>
</appender>
<root level="DEBUG">
<appender-ref ref="SOCKET" />
</root>
</configuration></pre>
<p>Note that, just as in the previous example, the values for
<span class="prop">remoteHost</span>, <span class="prop">port</span>
are specified using substituted variable keys. Additionally, note
the presence of the <span class="prop">ssl</span> property and its
nested <span class="prop">trustStore</span> property, which specifies
the location and password of a trust store using substituted
variables. This configuration is necessary because our example
server is using a self-signed certificate. See
<a href="usingSSL.html">Using SSL</a> for more information on
SSL configuration properties for <code>SSLSocketAppender</code>.
</p>
<p>We can run a client application using this configuration by
specifying the substitution variable values on the command line as
system properties:
</p>
<p class="source">java -Dhost=localhost -Dport=6000 \
-Dtruststore=file:src/main/java/chapters/appenders/socket/ssl/truststore.jks \
-Dpassword=changeit \
chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/ssl/client.xml
</p>
<p>As in the previous examples, you can type in a message when
prompted by the client application, and the message will be delivered
to the logging server (now over a secure channel) where it will be
displayed on the console.
</p>
<p>Note that the <em>truststore</em> property given on the command
line specifies a file URL that identifies the location of the
trust store. You may also use a classpath URL as described in <a
href="usingSSL.html">Using SSL</a>.
</p>
<p>As we saw previously at server startup, because the client
configuration has <code>debug="true"</code> specified on the root
element, the client's startup logging includes the details of the
SSL configuration as aid to auditing local policy conformance.
</p>
<h3 class="doAnchor" name="serverSocketAppender">
ServerSocketAppender and SSLServerSocketAppender</h3>
<p>The <code>SocketAppender</code> component (and its SSL-enabled
counterpart) discussed previously are designed to allow an
application to connect to a remote logging server over the network
for the purpose of delivering logging events to the server. In
some situations, it may be inconvenient or infeasible to have an
application initiate a connection to a remote logging server. For
these situations, Logback offers <a
href="../xref/ch/qos/logback/classic/net/server/ServerSocketAppender">
<code>ServerSocketAppender</code></a>.
</p>
<p>Instead of initiating a connection to a remote logging server,
<code>ServerSocketAppender</code> passively listens on a TCP socket
awaiting incoming connections from remote clients. Logging events
that are delivered to the appender are distributed to each connected
client. Logging events that occur when no client is connected are
<em>summarily discarded</em>.
</p>
<p>In addition to the basic <code>ServerSocketAppender</code>, Logback
offers <a href="../xref/ch/qos/logback/classic/net/server/SSLServerSocketAppender">
<code>SSLServerSocketAppender</code></a>, which distributes logging events
to each connected client using a secure, encrypted channel. Moreover, the
SSL-enabled appender fully supports mutual certificate-based authentication,
which can be used to ensure that only authorized clients can connect to
the appender to receive logging events.
</p>
<p>The approach to encoding logging events for transmission on the wire
is identical to that used by <code>SocketAppender</code>; each event is
a serialized instance of <code>ILoggingEvent</code>. Only the direction
of connection initiation is reversed. While <code>SocketAppender</code>
acts as the active peer in establishing the connection to a logging server,
<code>ServerSocketAppender</code> is passive; it listens for
incoming connections from clients.</p>
<p>The <code>ServerSocketAppender</code> subtypes are intended to be
used exclusively with Logback <em>receiver</em> components. See
<a href="receivers.html">Receivers</a> for additional information on
this component type.</p>
<p>The following configuration properties are supported by
<code>ServerSocketAppender</code>:</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="serverSocketAppender">address</span></td>
<td><code>String</code></td>
<td>The local network interface address on which the appender
will listen. If this property is not specified, the appender
will listen on all network interfaces.</td>
</tr>
<tr>
<td><span class="prop" container="serverSocketAppender">includeCallerData</span></td>
<td><code>boolean</code></td>
<td>
<p>
If true, the caller data will be available to the remote host.
By default no caller data is sent to the client.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="serverSocketAppender">port</span></td>
<td><code>int</code></td>
<td>
<p>
The port number on which the appender will listen.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="serverSocketAppender">ssl</span></td>
<td><code>SSLConfiguration</code></td>
<td>Supported only for <code>SSLServerSocketAppender</code>, this
property provides the SSL configuration that will be used by
the appender, as described in <a href="usingSSL.html">Using SSL</a>.
</td>
</tr>
</table>
<p>The following example illustrates a configuration that uses
<code>ServerSocketAppender</code>:
</p>
<p class="example">Example: Basic ServerSocketAppender Configuration
(logback-examples/src/main/resources/chapters/appenders/socket/server4.xml)</p>
<pre id="SocketReceiver" class="prettyprint source"><configuration debug="true">
<appender name="SERVER"
class="ch.qos.logback.classic.net.server.ServerSocketAppender">
<port>${port}</port>
<includeCallerData>${includeCallerData}</includeCallerData>
</appender>
<root level="debug">
<appender-ref ref="SERVER" />
</root>
</configuration>
</pre>
<p>Note that this configuration differs from previous examples using
<code>SocketAppender</code> only in the <em>class</em> specified for
the appender, and in the absence of the <span class="prop">remoteHost</span>
property — this appender waits passively for inbound connections
from remote hosts rather than opening a connection to a remote logging
server.
</p>
<p>The following example illustrates a configuration using
<code>SSLServerSocketAppender</code>.</p>
<p class="example">Example: Basic SSLServerSocketAppender Configuration
(logback-examples/src/main/resources/chapters/appenders/socket/ssl/server3.xml)</p>
<pre id="SocketReceiver" class="prettyprint source"><configuration debug="true">
<appender name="SERVER"
class="ch.qos.logback.classic.net.server.SSLServerSocketAppender">
<port>${port}</port>
<includeCallerData>${includeCallerData}</includeCallerData>
<ssl>
<keyStore>
<location>${keystore}</location>
<password>${password}</password>
</keyStore>
</ssl>
</appender>
<root level="debug">
<appender-ref ref="SERVER" />
</root>
</configuration>
</pre>
<p>The principal differences between this configuration and the
previous configuration is that the appender's <em>class</em> attribute
identifies the <code>SSLServerSocketAppender</code> type, and the
presence of the nested <span class="prop">ssl</span> element which
specifies, in this example, configuration of a key store containing
an X.509 credential for the appender. See <a href="usingSSL.html">
Using SSL</a> for information regarding SSL configuration properties.
</p>
<p>Because the <code>ServerSocketAppender</code> subtypes are designed
to be used with receiver components, we will defer presenting
illustrative examples to the chapter entitled
<a href="receivers.html">Receivers</a>.</p>
<h3 class="doAnchor">SMTPAppender</h3>
<p>The <a
href="../xref/ch/qos/logback/classic/net/SMTPAppender.html"><code>SMTPAppender</code></a>
accumulates logging events in one or more fixed-size buffers and
sends the contents of the appropriate buffer in an email after a
user-specified event occurs. SMTP email transmission (sending) is
performed asynchronously. By default, the email transmission is
triggered by a logging event of level ERROR. Moreover, by default,
a single buffer is used for all events.
</p>
<p>The various properties for <code>SMTPAppender</code> are
summarized in the following table.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="smtp">smtpHost</span></td>
<td><code>String</code></td>
<td>The host name of the SMTP server. This parameter is mandatory.</td>
</tr>
<tr>
<td><span class="prop" container="smtp">smtpPort</span></td>
<td><code>int</code></td>
<td>The port where the SMTP server is listening. Defaults to
25.</td>
</tr>
<tr>
<td><span class="prop" name="smtpTo">to</span></td>
<td><code>String</code></td>
<td>The email address of the recipient as a
<em>pattern</em>. The pattern is evaluated anew with the
triggering event as input for each outgoing email. Multiple
recipients can be specified by separating the destination
addresses with commas. Alternatively, multiple recipients can
also be specified by using multiple <code><to></code>
elements.
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">from</span></td>
<td><code>String</code></td>
<td>The originator of the email messages sent by
<code>SMTPAppender</code> in the <a
href="http://en.wikipedia.org/wiki/Email_address">usual email
address format</a>. If you wish to include the sender's name,
then use the format
"Adam Smith &lt;smith@moral.org&gt;" so that
the message appears as originating from
"Adam Smith <smith@moral.org>".
</td>
</tr>
<tr>
<td><span class="prop">subject</span></td>
<td><code>String</code></td>
<td>
<p>The subject of the email. It can be any value accepted as
a valid conversion pattern by <a
href="layouts.html#ClassicPatternLayout">PatternLayout</a>. Layouts
will be discussed in the next chapter.
</p>
<p>The outgoing email message will have a subject line
corresponding to applying the pattern on the logging event
that triggered the email message.
</p>
<p>Assuming the <span class="prop">subject</span> option
is set to "Log: %logger - %msg" and the triggering event's
logger is named "com.foo.Bar", and contains the message
"Hello world", then the outgoing email will have the subject
line "Log: com.foo.Bar - Hello World".
</p>
<p>By default, this option is set to "%logger{20} - %m".</p>
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">discriminator</span></td>
<td><code><a href="../xref/ch/qos/logback/core/sift/Discriminator.html">Discriminator</a></code></td>
<td>
<p>With the help of a <span
class="prop">Discriminator</span>,
<code>SMTPAppender</code> can scatter incoming events into
different buffers according to the value returned by the
discriminator. The default discriminator always returns the
same value so that the same buffer is used for all events.
</p>
<p>By specifying a discriminator other than the default
one, it is possible to receive email messages
containing a events pertaining to a particular user, user
session or client IP address.
</p>
</td>
</tr>
<tr>
<td><span class="prop" name="smtpAppender_Evaluator">evaluator</span></td>
<td><code><a
href="../xref/ch/qos/logback/classic/boolex/IEvaluator.html">IEvaluator</a></code></td>
<td>
<p>This option is declared by creating a new
<code><EventEvaluator/></code> element. The name of the
class that the user wishes to use as the
<code>SMTPAppender</code>'s <code>Evaluator</code> needs
to be specified via the <span class="attr">class</span>
attribute.
</p>
<p>In the absence of this option, <code>SMTPAppender</code>
is assigned an instance of <a
href="../xref/ch/qos/logback/classic/boolex/OnErrorEvaluator.html">OnErrorEvaluator</a>
which triggers email transmission when it encounters an
event of level <em>ERROR</em> or higher.
</p>
<!--
<p><code>EventEvaluator</code> objects are subclasses of the
<code>JaninoEventEvaluatorBase</code> which depends on
Janino. See the <a href="../dependencies.html">dependencies
page</a> for more information.
</p>
-->
<p>Logback ships with several other evaluators, namely <a
href="../xref/ch/qos/logback/classic/boolex/OnMarkerEvaluator.html"><code>OnMarkerEvaluator</code></a>
(discussed below) and a powerful evaluator called <a
href="../xref/ch/qos/logback/classic/boolex/JaninoEventEvaluator.html"><code>JaninoEventEvaluator</code></a>,
discussed in <a href="filters.html#evalutatorFilter">another
chapter</a>. The more recent versions of logback ship with
an even more powerful evaluator called <a
href="filters.html#GEventEvaluator"><code>GEventEvaluator</code></a>.
</p>
</td>
</tr>
<tr>
<td valign="top"><span class="prop" container="smtp">cyclicBufferTracker</span></td>
<td><a href="../xref/ch/qos/logback/core/spi/CyclicBufferTracker.html"><code>CyclicBufferTracker</code></a>
</td>
<td>
<p>As the name indicates, an instance of the
<code>CyclicBufferTracker</code> class tracks cyclic
buffers. It does so based on the keys returned by the <span
class="prop">discriminator</span> (see above).
</p>
<p>If you don't specify a <span
class="prop">cyclicBufferTracker</span>, an instance of <a
href="../xref/ch/qos/logback/core/spi/CyclicBufferTracker.html">CyclicBufferTracker</a>
will be automatically created. By default, this instance
will keep events in a cyclic buffer of size 256. You may
change the size with the help of the <span
class="prop">bufferSize</span> option (see below).</p>
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">username</span></td>
<td><code>String</code></td> <td>The username value to use
during plain user/password authentication. By default, this
parameter is null. </td>
</tr>
<tr class="alt">
<td><span class="prop" container="smtp">password</span></td>
<td><code>String</code></td>
<td>The password value to use for plain user/password
authentication. By default, this parameter is null.
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">STARTTLS</span> </td>
<td><code>boolean</code></td>
<td>If this parameter is set to true, then this appender
will issue the STARTTLS command (if the server supports it)
causing the connection to switch to SSL. Note that the
connection is initially non-encrypted. By default, this
parameter is set to false.
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">SSL</span></td>
<td><code>boolean</code></td> <td>If this parameter is set to
true, then this appender will open an SSL connection to the
server. By default, this parameter is set to false. </td>
</tr>
<tr>
<td><span class="prop" container="smtp">charsetEncoding</span></td>
<td><code>String</code></td>
<td>The outgoing email message will be encoded in the
designated <a
href="https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html">charset</a>. The
default charset encoding is "UTF-8" which works well for most
purposes.
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">localhost</span></td>
<td><code>String</code></td>
<td>In case the hostname of the SMTP client is not properly
configured, e.g. if the client hostname is not fully
qualified, certain SMTP servers may reject the HELO/EHLO
commands sent by the client. To overcome this issue, you may
set the value of the <span class="prop">localhost</span>
property to the fully qualified name of the client host. See
also the "mail.smtp.localhost" property in the documentation
for the <a
href="http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html">com.sun.mail.smtp</a>
package.</td>
</tr>
<tr>
<td><span class="prop" container="smtp">asynchronousSending</span></td>
<td><code>boolean</code></td>
<td>This property determines whether email transmission is
done asynchronously or not. By default, the <span
class="prop">asynchronousSending</span> property is
'true'. However, under certain circumstances asynchronous
sending may be inappropriate. For example if your application
uses <code>SMTPAppender</code> to send alerts in response to a
fatal error, and then exits, the relevant thread may not have
the time to send the alert email. In this case, set <span
class="prop">asynchronousSending</span> property to 'false'
for synchronous email transmission.
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">includeCallerData</span></td>
<td><code>boolean</code></td>
<td>By default, <span class="prop">includeCallerData</span> is
set to <code>false</code>. You should set <span
class="prop">includeCallerData</span> to <code>true</code> if
<span class="prop">asynchronousSending</span> is enabled and
you wish to include caller data in the logs. </td>
</tr>
<tr>
<td><span class="prop" container="smtp">sessionViaJNDI</span></td>
<td><code>boolean</code></td>
<td><code>SMTPAppender</code> relies on
<code>javax.mail.Session</code> to send out email messages. By
default, <span class="prop">sessionViaJNDI</span> is set to
<code>false</code> so the <code>javax.mail.Session</code>
instance is built by <code>SMTPAppender</code> itself with the
properties specified by the user. If the <span
class="prop">sessionViaJNDI</span> property is set to
<code>true</code>, the <code>javax.mail.Session</code> object
will be retrieved via JNDI. See also the <span
class="prop">jndiLocation</span> property.
<p>Retrieving the <code>Session</code> via JNDI can reduce the
number of places you need to configure/reconfigure the same
information, making your application <a
href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dryer</a>. For
more information on configuring resources in Tomcat see <a
href="http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html#JavaMail_Sessions">JNDI
Resources How-to</a>. <span class="label">beware</span> As
noted in that document, make sure to remove <em>mail.jar</em>
and <em>activation.jar</em> from your web-applications
<em>WEB-INF/lib</em> folder when retrieving the
<code>Session</code> from JNDI.
</p>
</td>
</tr>
<tr>
<td><span class="prop" container="smtp">jndiLocation</span></td>
<td><code>String</code></td>
<td>The location where the javax.mail.Session is placed in
JNDI. By default, <span class="prop">jndiLocation</span> is
set to <span style="white-space:nowrap">"java:comp/env/mail/Session"</span>.
</td>
</tr>
</table>
<p>The <code>SMTPAppender</code> keeps only the last 256 logging
events in its cyclic buffer, throwing away older events when its
buffer becomes full. Thus, the number of logging events delivered
in any e-mail sent by <code>SMTPAppender</code> is upper-bounded
by 256. This keeps memory requirements bounded while still
delivering a reasonable amount of application context.
</p>
<p>The <code>SMTPAppender</code> relies on the JavaMail API. It
has been tested with JavaMail API version 1.4. The JavaMail API
requires the JavaBeans Activation Framework package. You can
download the <a
href="http://java.sun.com/products/javamail/">JavaMail API</a> and
the <a
href="http://java.sun.com/beans/glasgow/jaf.html">JavaBeans
Activation Framework</a> from their respective websites. Make
sure to place these two jar files in the classpath before trying
the following examples.
</p>
<p>A sample application, <a
href="../xref/chapters/appenders/mail/EMail.html"><code>chapters.appenders.mail.EMail</code></a>
generates a number of log messages followed by a single
error message. It takes two parameters. The first parameter is an
integer corresponding to the number of logging events to
generate. The second parameter is the logback configuration
file. The last logging event generated by <em>EMail</em>
application, an ERROR, will trigger the transmission of an email
message.
</p>
<p>Here is a sample configuration file intended for the
<code>Email</code> application:
</p>
<p class="example">Example: A sample <code>SMTPAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/mail/mail1.xml)</p>
<span class="asGroovy" onclick="return asGroovy('mail1');">View as .groovy</span>
<pre id="mail1" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>ADDRESS-OF-YOUR-SMTP-HOST</smtpHost>
<to>EMAIL-DESTINATION</to>
<to>ANOTHER_EMAIL_DESTINATION</to> <!-- additional destinations are possible -->
<from>SENDER-EMAIL</from>
<subject>TESTING: %logger{20} - %m</subject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date %-5level %logger{35} - %message%n</pattern>
</layout>
</appender>
<root level="DEBUG">
<appender-ref ref="EMAIL" />
</root>
</configuration></pre>
<p>Before trying out <code>chapters.appenders.mail.Email</code> application
with the above configuration file, you must set the <span
class="prop">smtpHost</span>, <span class="prop">to</span> and
<span class="prop">from</span> properties to values appropriate for
your environment. Once you have set the correct values in the
configuration file, execute the following command:
</p>
<div class="source"><pre>java chapters.appenders.mail.EMail 100 src/main/java/chapters/appenders/mail/mail1.xml</pre></div>
<p>The recipient you specified should receive an email message
containing 100 logging events formatted by
<code>PatternLayout</code> The figure below is the resulting email
message as shown by Mozilla Thunderbird.
</p>
<p><img src="images/chapters/appenders/smtpAppender1.jpg" alt="resulting email"/></p>
<p>In the next example configuration file <em>mail2.xml</em>, the
values for the <span class="prop">smtpHost</span>, <span
class="prop">to</span> and <span class="prop">from</span>
properties are determined by variable substitution. Here is the
relevant part of <em>mail2.xml</em>.
</p>
<pre class="prettyprint source"><appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>${smtpHost}</smtpHost>
<to>${to}</to>
<from>${from}</from>
<layout class="ch.qos.logback.classic.html.HTMLLayout"/>
</appender></pre>
<p>You can pass the required parameters on the command line:</p>
<div class="source"><pre>java -Dfrom=source@xyz.com -Dto=recipient@xyz.com -DsmtpHost=some_smtp_host \
chapters.appenders.mail.EMail 10000 src/main/java/chapters/appenders/mail/mail2.xml
</pre></div>
<p>Be sure to replace with values as appropriate for your
environment.
</p>
<p>Note that in this latest example, <code>PatternLayout</code>
was replaced by <code>HTMLLayout</code> which formats logs as an
HTML table. You can change the list and order of columns as well
as the CSS of the table. Please refer to <a
href="layouts.html#ClassicHTMLLayout">HTMLLayout</a> documentation
for further details.
</p>
<p>Given that the size of the cyclic buffer is 256, the recipient
should see an email message containing 256 events conveniently
formatted in an HTML table. Note that this run of the
<code>chapters.appenders.mail.Email</code> application generated
10'000 events of which only the last 256 were included in the
outgoing email.
</p>
<p><img src="images/chapters/appenders/smtpAppender2.jpg" alt="2nd email"/></p>
<p>Email clients such as Mozilla Thunderbird, Eudora or MS
Outlook, offer reasonably good CSS support for HTML email.
However, they sometimes automatically downgrade HTML to
plaintext. For example, to view HTML email in Thunderbird, the
"View→Message Body As→Original HTML" option
must be set. Yahoo! Mail's support for HTML email, in particular
its CSS support is very good. Gmail on the other hand, while it
honors the basic HTML table structure, ignores the internal CSS
formatting. Gmail supports inline CSS formatting but since inline
CSS would make the resulting output too voluminous,
<code>HTMLLayout</code> does not use inline CSS.
</p>
<h3 class="doAnchor" name="cyclicBufferSize">Custom buffer
size</h3>
<p>By default, the outgoing message will contain the last 256
messages seen by <code>SMTPAppender</code>. If your heart so
desires, you may set a different buffer size as shown in the next example.
</p>
<p class="example">Example: <code>SMTPAppender</code> configuration with a custom bufer size (logback-examples/src/main/resources/chapters/appenders/mail/customBufferSize.xml)</p>
<pre class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>${smtpHost}</smtpHost>
<to>${to}</to>
<from>${from}</from>
<subject>%logger{20} - %m</subject>
<layout class="ch.qos.logback.classic.html.HTMLLayout"/>
<b><cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker"></b>
<b><!-- send just one log entry per email --></b>
<b><bufferSize>1</bufferSize></b>
<b></cyclicBufferTracker></b>
</appender>
<root level="DEBUG">
<appender-ref ref="EMAIL" />
</root>
</configuration> </pre>
<h3 class="doAnchor">Triggering event</h3>
<p>If the Evaluator property is not set, the
<code>SMTPAppender</code> defaults to an <a
href="../xref/ch/qos/logback/classic/boolex/OnErrorEvaluator.html">OnErrorEvaluator</a>
instance which triggers email transmission when it encounters an
event of level ERROR. While triggering an outgoing email in
response to an error is relatively reasonable, it is possible to
override this default behavior by providing a different
implementation of the <code>EventEvaluator</code> interface.
</p>
<p>The <code>SMTPAppender</code> submits each incoming event to
its evaluator by calling <code>evaluate()</code> method in order
to check whether the event should trigger an email or just be
placed in the cyclic buffer. When the evaluator gives a positive
answer to its evaluation, an email is sent out. The
<code>SMTPAppender</code> contains one and only one evaluator
object. This object may manage its own internal state. For
illustrative purposes, the <code>CounterBasedEvaluator</code>
class listed next implements an event evaluator whereby every
1024th event triggers an email message.
</p>
<p class="example">Example: A <code>EventEvaluator</code> implementation
that evaluates to <code>true</code> every 1024th event (<a href="../xref/chapters/appenders/mail/CounterBasedEvaluator.html">logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java</a>)</p>
<pre class="prettyprint source">package chapters.appenders.mail;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluator;
import ch.qos.logback.core.spi.ContextAwareBase;
public class CounterBasedEvaluator extends ContextAwareBase implements EventEvaluator {
static int LIMIT = 1024;
int counter = 0;
String name;
<b>public boolean evaluate(Object event) throws NullPointerException,
EvaluationException {
counter++;
if (counter == LIMIT) {
counter = 0;
return true;
} else {
return false;
}
}</b>
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}</pre>
<p>Note that this class extends <code>ContextAwareBase</code> and
implements <code>EventEvaluator</code>. This allows the user to
concentrate on the core functions of her
<code>EventEvaluator</code> and let the base class provide the
common functionality.
</p>
<p>Setting the <span class="prop">Evaluator</span> option of
<code>SMTPAppender</code> instructs it to use a custom evaluator.
The next configuration file attaches a <code>SMTPAppender</code>
to the root logger. This appender uses a
<code>CounterBasedEvaluator</code> instance as its event
evaluator.
</p>
<p class="example">Example: <code>SMTPAppender</code> with custom
<code>Evaluator</code> and buffer size (logback-examples/src/main/resources/chapters/appenders/mail/mail3.xml)</p>
<span class="asGroovy" onclick="return asGroovy('mail3');">View as .groovy</span>
<pre id="mail3" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<b><evaluator class="chapters.appenders.mail.CounterBasedEvaluator" /></b>
<smtpHost>${smtpHost}</smtpHost>
<to>${to}</to>
<from>${from}</from>
<subject>%logger{20} - %m</subject>
<layout class="ch.qos.logback.classic.html.HTMLLayout"/>
</appender>
<root level="DEBUG">
<appender-ref ref="EMAIL" />
</root>
</configuration></pre>
<h3 class="doAnchor" name="OnMarkerEvaluator">Marker based
triggering </h3>
<p>Although reasonable, the default triggering policy whereby every
event of level ERROR triggers an outgoing email may result in too
many emails, cluttering the targeted user's mailbox. Logback ships
with another triggering policy, called <a
href="../xref/ch/qos/logback/classic/boolex/OnMarkerEvaluator.html">OnMarkerEvaluator</a>. It
is based on markers. In essence, emails are triggered only if the
event is marked with a user-specified marker. The next example
should make the point clearer.
</p>
<p>The <a
href="../xref/chapters/appenders/mail/Marked_EMail.html">Marked_EMail</a>
application contains several logging statements some of which are
of level ERROR. One noteworthy statement contains a marker. Here
is the relevant code.
</p>
<pre class="prettyprint source">Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN");
logger.error(<b>notifyAdmin</b>,
"This is a serious an error requiring the admin's attention",
new Exception("Just testing"));</pre>
<p>The next configuration file will trigger outgoing emails only in
presence of events bearing the NOTIFY_ADMIN or the
TRANSACTION_FAILURE markers.
</p>
<p class="example">Example: <code>SMTPAppender</code> with
<code>OnMarkerEvaluator</code> (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMarker.xml)</p>
<span class="asGroovy" onclick="return asGroovy('mailWithMarker');">View as .groovy</span>
<pre id="mailWithMarker" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<b><evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
<marker>NOTIFY_ADMIN</marker>
<!-- you specify add as many markers as you want -->
<marker>TRANSACTION_FAILURE</marker>
</evaluator></b>
<smtpHost>${smtpHost}</smtpHost>
<to>${to}</to>
<from>${from}</from>
<layout class="ch.qos.logback.classic.html.HTMLLayout"/>
</appender>
<root>
<level value ="debug"/>
<appender-ref ref="EMAIL" />
</root>
</configuration></pre>
<p>Give it a whirl with the following command:</p>
<pre class="source">java -Dfrom=source@xyz.com -Dto=recipient@xyz.com -DsmtpHost=some_smtp_host \
chapters.appenders.mail.Marked_EMail src/main/java/chapters/appenders/mail/mailWithMarker.xml</pre>
<h4 class="doAnchor" name="marker_JaninoEventEvaluator">Marker-based
triggering with JaninoEventEvaluator</h4>
<p>Note that instead of using the marker-centric
<code>OnMarkerEvaluator</code>, we could use the much more generic
<a
href="filters.html#JaninoEventEvaluator"><code>JaninoEventEvaluator</code></a>
or its even more powerful cousin <a
href="filters.html#GEventEvaluator"><code>GEventEvaluator</code></a>.
For example, the following configuration file uses
<code>JaninoEventEvaluator</code> instead of
<code>OnMarkerEvaluator</code> but is otherwise equivalent to the
previous configuration file.
</p>
<p class="example">Example: <code>SMTPAppender</code> with
<code>JaninoEventEvaluator</code> (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMarker_Janino.xml)</p>
<span class="asGroovy" onclick="return asGroovy('mailWithMarker_Janino');">View as .groovy</span>
<pre id="mailWithMarker_Janino" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>
(marker != null) &&
(marker.contains("NOTIFY_ADMIN") || marker.contains("TRANSACTION_FAILURE"))
</expression>
</evaluator>
... same as above
</appender>
</configuration></pre>
<h4 class="doAnchor" name="marker_GEventEvaluator">Marker-based
triggering with GEventEvaluator</h4>
<p>Here is the equivalent evaluator using <a
href="filters.html#GEventEvaluator">GEventEvaluator</a>.</p>
<p class="example">Example: the same with
<code>GEventEvaluator</code> (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMarker_GEvent.xml)</p>
<span class="asGroovy" onclick="return asGroovy('mailWithMarker_GEventEvaluator');">View as .groovy</span>
<pre id="mailWithMarker_GEventEvaluator" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator">
<expression>
e.marker?.contains("NOTIFY_ADMIN") || e.marker?.contains("TRANSACTION_FAILURE")
</expression>
</evaluator>
... same as above
</appender>
</configuration></pre>
<p>Note that since the event may lack a marker, the value of
e.marker can be null. Hence the use of Groovy's <a
href="http://groovy.codehaus.org/Null+Object+Pattern">safe
dereferencing operator</a>, that is the .? operator.
</p>
<h3 class="doAnchor" name="smtpAuthentication">Authentication/STARTTLS/SSL</h3>
<p><code>SMTPAppender</code> supports authentication via plain
user passwords as well as both the STARTTLS and SSL
protocols. Note that STARTTLS differs from SSL in that, in
STARTTLS, the connection is initially non-encrypted and only after
the STARTTLS command is issued by the client (if the server
supports it) does the connection switch to SSL. In SSL mode, the
connection is encrypted right from the start.
</p>
<h3 class="doAnchor" name="gmailSSL">SMTPAppender configuration
for Gmail (SSL)</h3>
<p>The next example shows you how to configure
<code>SMTPAppender</code> for Gmail with the SSL protocol. </p>
<p class="example">Example:: <code>SMTPAppender</code> to Gmail
using SSL
(logback-examples/src/main/resources/chapters/appenders/mail/gmailSSL.xml)</p>
<span class="asGroovy" onclick="return asGroovy('gmailSSLExample');">View as .groovy</span>
<pre id="gmailSSLExample" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<b><smtpHost>smtp.gmail.com</smtpHost></b>
<b><smtpPort>465</smtpPort></b>
<b><SSL>true</SSL></b>
<b><username>YOUR_USERNAME@gmail.com</username></b>
<b><password>YOUR_GMAIL_PASSWORD</password></b>
<to>EMAIL-DESTINATION</to>
<to>ANOTHER_EMAIL_DESTINATION</to> <!-- additional destinations are possible -->
<from>YOUR_USERNAME@gmail.com</from>
<subject>TESTING: %logger{20} - %m</subject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date %-5level %logger{35} - %message%n</pattern>
</layout>
</appender>
<root level="DEBUG">
<appender-ref ref="EMAIL" />
</root>
</configuration></pre>
<h3 class="doAnchor" name="gmailSTARTTLS">SMTPAppender for Gmail
(STARTTLS)</h3>
<p>The next example shows you how to configure
<code>SMTPAppender</code> for Gmail for the STARTTLS protocol. </p>
<p class="example">Example: <code>SMTPAppender</code> to GMAIL using STARTTLS (logback-examples/src/main/resources/chapters/appenders/mail/gmailSTARTTLS.xml)</p>
<span class="asGroovy" onclick="return asGroovy('gmailSTARTTLSExample');">View as .groovy</span>
<pre id="gmailSTARTTLSExample" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>smtp.gmail.com</smtpHost>
<smtpPort>587</smtpPort>
<STARTTLS>true</STARTTLS>
<username>YOUR_USERNAME@gmail.com</username>
<password>YOUR_GMAIL_xPASSWORD</password>
<to>EMAIL-DESTINATION</to>
<to>ANOTHER_EMAIL_DESTINATION</to> <!-- additional destinations are possible -->
<from>YOUR_USERNAME@gmail.com</from>
<subject>TESTING: %logger{20} - %m</subject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date %-5level %logger - %message%n</pattern>
</layout>
</appender>
<root level="DEBUG">
<appender-ref ref="EMAIL" />
</root>
</configuration></pre>
<h3 class="doAnchor" name="smtpDiscriminator">SMTPAppender with MDCDiscriminator</h3>
<p>As mentioned earlier, by specifying a discriminator other than
the default one, <code>SMTPAppender</code> will generate email
messages containing events pertaining to a particular user, user
session or client IP address, depending on the specified discriminator.
</p>
<p>The next example illustrates the use of <a
href="../xref/ch/qos/logback/classic/sift/MDCBasedDiscriminator.html">MDCBasedDiscriminator</a>
in conjunction with the MDC key named "req.remoteHost", assumed to
contain the IP address of the remote host accessing a fictitious
application. In a web-application, you could use <a
href="mdc.html#mis">MDCInsertingServletFilter</a> to populate MDC
values.
</p>
<p class="example">Example: <code>SMTPAppender</code> with
MDCBasedDsicriminator
(logback-examples/src/main/resources/chapters/appenders/mail/mailWithMDCBasedDiscriminator.xml)</p>
<span class="asGroovy" onclick="return asGroovy('mailWithMDCBasedDiscriminator');">View as .groovy</span>
<pre id="mailWithMDCBasedDiscriminator" class="prettyprint source"><configuration>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>ADDRESS-OF-YOUR-SMTP-HOST</smtpHost>
<to>EMAIL-DESTINATION</to>
<from>SENDER-EMAIL</from>
<b><discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator"></b>
<b><key>req.remoteHost</key></b>
<b><defaultValue>default</defaultValue></b>
<b></discriminator></b>
<subject>${HOSTNAME} -- %X{req.remoteHost} %msg"</subject>
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%date%level%thread%X{req.remoteHost}%X{req.requestURL}%logger%msg</pattern>
</layout>
</appender>
<root>
<level level="DEBUG"/>
<appender-ref ref="EMAIL" />
</root>
</configuration></pre>
<p>Thus, each outgoing email generated by
<code>SMTPAppender</code> will belong to a <em>unique</em> remote
host, greatly facilitating problem diagnosis.
</p>
<h4 class="doAnchor" name= "bufferManagement">Buffer management in
very busy systems</h4>
<p>Internally, each distinct value returned by the discriminator
will cause the creation of a new cyclic buffer. However, at most
<span class="prop">maxNumberOfBuffers</span> (by default 64)
will be maintained. Whenever the number of buffers rises above
<span class="prop">maxNumberOfBuffers</span>, the least recently
updated buffer is automatically discarded. As a second safety
measure, any buffer which has not been updated in the last 30
minutes will be automatically discarded as well.</p>
<p>On systems serving a large number of transactions per minute,
allowing only a small number for <span
class="prop">maxNumberOfBuffers</span> (by default 64) will
often cause the number of events in the outgoing email to be
unnecessarily small. Indeed, in the presence of a large number of
transactions, there will be more than one buffer associated with
the same transaction as buffers will be killed and re-born in
succession for the same discriminator value (or transaction). Note
that in even such very busy systems, the maximum number of cyclic
buffers is capped by <span
class="prop">maxNumberOfBuffers</span>.
</p>
<p>To avoid such yo-yo effects, <code>SMTPAppender</code> will
release the buffer associated with a given discriminator key as
soon as it sees an event marked as "FINALIZE_SESSION". This will
cause the appropriate buffer to be discarded at the end of each
transaction. You can then safely increase the value of <span
class="prop">maxNumberOfBuffers</span> to a larger value such as
512 or 1024 without risking running out of memory.
</p>
<p>There are three distinct but complementary mechanisms working
together to manage cyclic buffers. They ensure that only relevant
buffers are kept alive at any given moment, even in very busy
systems.</p>
<!-- =========================================================== -->
<!-- =========================================================== -->
<h3 class="doAnchor" name="DBAppender">DBAppender</h3>
<p>The <a
href="../xref/ch/qos/logback/classic/db/DBAppender.html"><code>DBAppender</code></a>
inserts logging events into three database tables in a format
independent of the Java programming language.
</p>
<p>These three tables are <em>logging_event</em>,
<em>logging_event_property</em> and
<em>logging_event_exception</em>. They must exist before
<code>DBAppender</code> can be used. Logback ships with SQL
scripts that will create the tables. They can be found under the
<em>logback-classic/src/main/java/ch/qos/logback/classic/db/script</em>
folder. There is a specific script for each of the most popular
database systems. If the script for your particular type of
database system is missing, it should be quite easy to write one,
taking example on the already existing scripts. If you send them
to us, we will gladly include missing scripts in future releases.
</p>
<p>If your JDBC driver supports the <code>getGeneratedKeys</code>
method introduced in JDBC 3.0 specification, assuming you have
created the appropriate database tables as mentioned above, then
no additional steps are required. Otherwise, there must be an
<code>SQLDialect</code> appropriate for your database
system. Currently, logback has dialects for H2, HSQL, MS SQL
Server, MySQL, Oracle, PostgreSQL, SQLLite and Sybase. </p>
<p>The table below summarizes the database types and their support
of the <code>getGeneratedKeys()</code> method.
</p>
<table class="bodyTable striped" border="0" cellpadding="4">
<tr>
<th>RDBMS</th>
<th>tested version(s)
</th>
<th>tested JDBC driver version(s)
</th>
<th>
supports
<br />
<code>getGeneratedKeys()</code>
method
</th>
<th>is a dialect <br/>provided by logback</th>
</tr>
<tr>
<td>DB2</td>
<td>untested</td>
<td>untested</td>
<td>unknown</td>
<td>NO</td>
</tr>
<tr>
<td>H2</td>
<td>1.2.132</td>
<td>-</td>
<td>unknown</td>
<td>YES</td>
</tr>
<tr>
<td>HSQL</td>
<td>1.8.0.7</td>
<td>-</td>
<td>NO </td>
<td>YES</td>
</tr>
<tr>
<td>Microsoft SQL Server</td>
<td>2005</td>
<td>2.0.1008.2 (sqljdbc.jar)</td>
<td>YES</td>
<td>YES</td>
</tr>
<tr>
<td>MySQL</td>
<td>5.0.22</td>
<td>5.0.8 (mysql-connector.jar)</td>
<td>YES</td>
<td>YES</td>
</tr>
<tr>
<td>PostgreSQL</td>
<td>8.x</td>
<td>8.4-701.jdbc4</td>
<td>NO</td>
<td>YES</td>
</tr>
<tr>
<td>Oracle</td>
<td>10g</td>
<td>10.2.0.1 (ojdbc14.jar)</td>
<td>YES</td>
<td>YES</td>
</tr>
<tr>
<td>SQLLite</td>
<td>3.7.4</td>
<td>-</td>
<td>unknown</td>
<td>YES</td>
</tr>
<tr>
<td>Sybase SQLAnywhere</td>
<td>10.0.1</td>
<td>-</td>
<td>unknown</td>
<td>YES</td>
</tr>
</table>
<p>Experiments show that writing a single event into the database
takes approximately 10 milliseconds, on a "standard" PC. If pooled
connections are used, this figure drops to around 1
millisecond. Note that most JDBC drivers already ship with
connection pooling support.
</p>
<p>Configuring logback to use <code>DBAppender</code> can be done
in several different ways, depending on the tools one has to
connect to the database, and the database itself. The key issue in
configuring <code>DBAppender</code> is about setting its
<code>ConnectionSource</code> object, as we shall discover
shortly.
</p>
<p>Once <code>DBAppender</code> is configured for your database,
logging events are sent to the specified database. As stated
previously, there are three tables used by logback to store
logging event data.
</p>
<p>
The <em>logging_event</em> table contains the following fields:
</p>
<table class="bodyTable striped">
<tr>
<th>Field</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><b>timestamp</b></td>
<td><code>big int</code></td>
<td>The timestamp that was valid at the logging event's creation.</td>
</tr>
<tr>
<td><b>formatted_message</b></td>
<td><code>text</code></td>
<td>The message that has been added to the logging event,
after formatting with
<code>org.slf4j.impl.MessageFormatter</code>, in case objects
were passed along with the message.</td>
</tr>
<tr>
<td><b>logger_name</b></td>
<td><code>varchar</code></td>
<td>The name of the logger used to issue the logging request.</td>
</tr>
<tr>
<td><b>level_string</b></td>
<td><code>varchar</code></td>
<td>The level of the logging event.</td>
</tr>
<tr>
<td><b>reference_flag</b></td>
<td><code>smallint</code></td>
<td>
<p>This field is used by logback to identify logging events
that have an exception or <code>MDC</code>property values
associated.
</p>
<p>Its value is computed by
<code>ch.qos.logback.classic.db.DBHelper</code>. A logging
event that contains <code>MDC</code> or <code>Context</code>
properties has a flag number of <em>1</em>. One that
contains an exception has a flag number of <em>2</em>. A
logging event that contains both elements has a flag number
of <em>3</em>.
</p>
</td>
</tr>
<tr>
<td><b>caller_filename</b></td>
<td><code>varchar</code></td>
<td>The name of the file where the logging request was issued.</td>
</tr>
<tr>
<td><b>caller_class</b></td>
<td><code>varchar</code></td>
<td>The class where the logging request was issued.</td>
</tr>
<tr>
<td><b>caller_method</b></td>
<td><code>varchar</code></td>
<td>The name of the method where the logging request was issued.</td>
</tr>
<tr>
<td><b>caller_line</b></td>
<td><code>char</code></td>
<td>The line number where the logging request was issued.</td>
</tr>
<tr>
<td><b>event_id</b></td>
<td><code>int</code></td>
<td>The database id of the logging event.</td>
</tr>
</table>
<p>
The <em>logging_event_property</em> is used to store the keys and values
contained in the <code>MDC</code> or the <code>Context</code>.
It contains these fields:
</p>
<table class="bodyTable striped">
<tr>
<th>Field</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><b>event_id</b></td>
<td><code>int</code></td>
<td>The database id of the logging event.</td>
</tr>
<tr>
<td><b>mapped_key</b></td>
<td><code>varchar</code></td>
<td>The key of the <code>MDC</code> property</td>
</tr>
<tr>
<td><b>mapped_value</b></td>
<td><code>text</code></td>
<td>The value of the <code>MDC</code> property</td>
</tr>
</table>
<p>
The <em>logging_event_exception</em> table contains the following fields:
</p>
<table class="bodyTable striped">
<tr>
<th>Field</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><b>event_id</b></td>
<td><code>int</code></td>
<td>The database id of the logging event.</td>
</tr>
<tr>
<td><b>i</b></td>
<td><code>smallint</code></td>
<td>The index of the line in the full stack trace.</td>
</tr>
<tr>
<td><b>trace_line</b></td>
<td><code>varchar</code></td>
<td>The corresponding line</td>
</tr>
</table>
<p>
To give a more visual example of the work done by <code>DBAppender</code>, here
is a screenshot of a MySQL database with content provided by <code>DBAppender</code>.
</p>
<p>The <em>logging_event</em> table:</p>
<img src="images/chapters/appenders/dbAppenderLE.gif" alt="Logging Event table" />
<p>The <em>logging_event_exception</em> table:</p>
<img src="images/chapters/appenders/dbAppenderLEException.gif" alt="Logging Event Exception table" />
<p>The <em>logging_event_property</em> table:</p>
<img src="images/chapters/appenders/dbAppenderLEProperty.gif" alt="Logging Event Property table" />
<h4>ConnectionSource</h4>
<p>The <code>ConnectionSource</code> interface provides a
pluggable means of transparently obtaining JDBC connections for
logback classes that require the use of a
<code>java.sql.Connection</code>. There are currently three
implementations of <code>ConnectionSource</code>, namely
<code>DataSourceConnectionSource</code>,
<code>DriverManagerConnectionSource</code> and
<code>JNDIConnectionSource</code>.
</p>
<p>
The first example that we will review is a configuration using
<code>DriverManagerConnectionSource</code> and a MySQL database.
The following configuration file is what one would need.
</p>
<p class="example">Example: <code>DBAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/db/append-toMySQL-with-driverManager.xml)</p>
<span class="asGroovy" onclick="return asGroovy('append-toMySQL-with-driverManager');">View as .groovy</span>
<pre id="append-toMySQL-with-driverManager" class="prettyprint source"><configuration>
<b><appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://host_name:3306/datebase_name</url>
<user>username</user>
<password>password</password>
</connectionSource>
</appender></b>
<root level="DEBUG" >
<appender-ref ref="DB" />
</root>
</configuration></pre>
<p>
The correct driver must be declared. Here, the <code>com.mysql.jdbc.Driver</code>
class is used. The <span class="prop">url</span> must begin with <em>jdbc:mysql://</em>.
</p>
<p>
The
<a href="../xref/ch/qos/logback/core/db/DriverManagerConnectionSource.html">
<code>DriverManagerConnectionSource</code></a> is an implementation of
<code>ConnectionSource</code> that obtains the connection in the
traditional JDBC manner based on the connection URL.
</p>
<p>
Note that this class will establish a new
<code>Connection</code> for each call to
<code>getConnection()</code>. It is recommended that you either
use a JDBC driver that natively supports connection pooling or
that you create your own implementation of
<code>ConnectionSource</code> that taps into whatever pooling
mechanism you are already using. If you have access to a JNDI
implementation that supports <code>javax.sql.DataSource</code>,
e.g. within a J2EE application server, see <a
href="#JNDIConnectionSource"><code>JNDIConnectionSource</code></a>
below.
</p>
<!--
HAS TO BE TESTED
<p>
If you do not have another connection pooling mechanism built
into your application, you can use the
<a href="http://jakarta.apache.org/commons/dbcp/index.html">
commons-dbcp </a> package from Apache:
</p>
<pre class="prettyprint source">
<connectionSource
class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<param name="driver" value="org.apache.commons.dbcp.PoolingDriver"/>
<param name="url" value="jdbc:apache:commons:dbcp:/myPoolingDriver"/>
</connectionSource>
</pre>
<p>
Then the configuration information for the commons-dbcp
package goes into the file <em>myPoolingDriver.jocl</em> and is
placed in the classpath. See the
<a href="http://jakarta.apache.org/commons/dbcp/index.html"> commons-dbcp </a>
documentation for details.
</p>
-->
<p>Connecting to a database using a <code>DataSource</code> is
rather similar. The configuration now uses <a
href="../xref/ch/qos/logback/core/db/DataSourceConnectionSource.html">
<code>DataSourceConnectionSource</code></a>, which is an
implementation of <code>ConnectionSource</code> that obtains the
<code>Connection</code> in the recommended JDBC manner based on a
<code>javax.sql.DataSource</code>.
</p>
<p class="example">Example: <code>DBAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/db/append-with-datasource.xml)</p>
<span class="asGroovy" onclick="return asGroovy('append-with-datasource');">View as .groovy</span>
<pre id="append-with-datasource" class="prettyprint source"><configuration debug="true">
<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
<b><connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
<dataSource class="${dataSourceClass}">
</b><!-- Joran cannot substitute variables
that are not attribute values. Therefore, we cannot
declare the next parameter like the others.
-->
<b><param name="${url-key:-url}" value="${url_value}"/>
<serverName>${serverName}</serverName>
<databaseName>${databaseName}</databaseName>
</dataSource></b>
<user>${user}</user>
<password>${password}</password>
</connectionSource>
</appender>
<root level="INFO">
<appender-ref ref="DB" />
</root>
</configuration></pre>
<p>Note that in this configuration sample, we make heavy use of
substitution variables. They are sometimes handy when connection
details have to be centralized in a single configuration file and
shared by logback and other frameworks.
</p>
<!-- TO BE TESTED
<p>The connection created by
<code>DataSourceConnectionSource</code> can be placed in a JNDI
context by using <code>BindDataSourceToJNDIAction</code>. In that
case, one has to specify the use of this class by adding a new
rule to Joran, logback's configuration framework. Here is an
excerpt of such a configuration file. </p>
<div class="source"><pre><configuration>
..
<b><newRule pattern="configuration/bindDataSourceToJNDI"
actionClass="ch.qos.logback.core.db.BindDataSourceToJNDIAction"/>
<bindDataSourceToJNDI /></b>
..
</configuration></pre></div>
<p> The <em>newRule</em> element teaches Joran to use specified
action class with the given pattern. Then, we simply declare the
given element. The action class will be called and our connection
source will be bound to a JNDI context. </p>
<p>This is a very powerful capability of Joran. If you'd like to
read more about Joran, please see the <a
href="onJoran.html">chapter to Joran</a>. </p>
-->
<h4 class="doAnchor"
name="JNDIConnectionSource">JNDIConnectionSource</h4>
<p><a
href="../xref/ch/qos/logback/core/db/JNDIConnectionSource.html">
<code>JNDIConnectionSource</code></a> is another
<code>ConnectionSource</code> implementation shipping in logback.
As its name indicates, it retrieves a
<code>javax.sql.DataSource</code> from a JNDI and then leverages
it to obtain a <code>java.sql.Connection</code>
instance. <code>JNDIConnectionSource</code> is primarily designed
to be used inside J2EE application servers or by application
server clients, assuming the application server supports remote
access of <code>javax.sql.DataSource</code>. Thus, one can take
advantage of connection pooling and whatever other goodies the
application server provides. More importantly, your application
will be <a
href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dryer</a>
as it will be no longer necessary to define a
<code>DataSource</code> in <em>logback.xml</em>.</p>
<p>For example, here is a configuration snippet for Tomcat. It
assumes PostgreSQL as the database although any of the supported
database systems (listed above) would work.</p>
<pre class="prettyprint source"><Context docBase="/path/to/app.war" path="/myapp">
...
<Resource <b>name="jdbc/logging"</b>
auth="Container"
type="javax.sql.DataSource"
username="..."
password="..."
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost/..."
maxActive="8"
maxIdle="4"/>
...
</Context></pre>
<p>Once a <code>DataSource</code> is defined in the J2EE server, it
can be easily referenced by your logback configuration file, as
shown in the next example.</p>
<p class="example">Example: <code>DBAppender</code> configuration
by <code>JNDIConnectionSource</code>
(logback-examples/src/main/resources/chapters/appenders/db/append-via-jndi.xml)</p>
<span class="asGroovy" onclick="return asGroovy('append-via-jndi');">View as .groovy</span>
<pre id="append-via-jndi" class="prettyprint source"><configuration debug="true">
<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource class="ch.qos.logback.core.db.JNDIConnectionSource">
<b><!-- please note the "java:comp/env/" prefix --></b>
<b><jndiLocation>java:comp/env/jdbc/logging</jndiLocation></b>
</connectionSource>
</appender>
<root level="INFO">
<appender-ref ref="DB" />
</root>
</configuration></pre>
<p>
Note that this class will obtain an
<code>javax.naming.InitialContext</code>
using the no-argument constructor. This will usually work
when executing within a J2EE environment. When outside the
J2EE environment, make sure that you provide a
<em>jndi.properties</em>
file as described by your JNDI provider's documentation.
</p>
<h4 class="doAnchor">Connection pooling</h4>
<p>Logging events can be created at a rather fast pace. To keep up
with the flow of events that must be inserted into a database, it
is recommended to use connection pooling with
<code>DBAppender</code>.
</p>
<p>
Experiment shows that using connection pooling with <code>DBAppender</code>
gives a big performance boost. With the following
configuration file, logging events are sent to a MySQL database,
without any pooling.
</p>
<p class="example">Example: <code>DBAppender</code> configuration
without pooling
(logback-examples/src/main/resources/chapters/appenders/db/append-toMySQL-with-datasource.xml)</p>
<span class="asGroovy" onclick="return asGroovy('append-toMySQL-with-datasource');">View as .groovy</span>
<pre id="append-toMySQL-with-datasource" class="prettyprint source"><configuration>
<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
<dataSource class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
<serverName>${serverName}</serverName>
<port>${port$</port>
<databaseName>${dbName}</databaseName>
<user>${user}</user>
<password>${pass}</password>
</dataSource>
</connectionSource>
</appender>
<root level="DEBUG">
<appender-ref ref="DB" />
</root>
</configuration></pre>
<p>With this configuration file, sending 500 logging events to a
MySQL database takes a whopping 5 seconds, that is 10 milliseconds
per request. This figure is unacceptable when dealing with large
applications.
</p>
<p>A dedicated external library is necessary to use connection
pooling with <code>DBAppender</code>. The next example uses <a
href="http://sourceforge.net/projects/c3p0">c3p0</a>. To be able
to use c3p0, one must download it and place
<em>c3p0-VERSION.jar</em> in the classpath.
</p>
<p class="example">Example: <code>DBAppender</code> configuration
with pooling
(logback-examples/src/main/resources/chapters/appenders/db/append-toMySQL-with-datasource-and-pooling.xml)</p>
<span class="asGroovy" onclick="return asGroovy('append-toMySQL-with-datasource-and-pooling');">View as .groovy</span>
<pre id="append-toMySQL-with-datasource-and-pooling" class="prettyprint source"><configuration>
<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource
class="ch.qos.logback.core.db.DataSourceConnectionSource">
<b><dataSource
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<driverClass>com.mysql.jdbc.Driver</driverClass>
<jdbcUrl>jdbc:mysql://${serverName}:${port}/${dbName}</jdbcUrl>
<user>${user}</user>
<password>${password}</password>
</dataSource></b>
</connectionSource>
</appender>
<root level="DEBUG">
<appender-ref ref="DB" />
</root>
</configuration></pre>
<p>With this new configuration, sending 500 logging requests to
the aforementioned MySQL database takes around 0.5 seconds, for an
average of 1 millisecond per request, that is a tenfold
improvement in performance.
</p>
<h3 class="doAnchor" name="SyslogAppender">SyslogAppender</h3>
<p>The syslog protocol is a very simple protocol: a syslog sender
sends a small message to a syslog receiver. The receiver is
commonly called <em>syslog daemon</em> or <em>syslog server</em>.
Logback can send messages to a remote syslog daemon. This is
achieved by using <a
href="../xref/ch/qos/logback/classic/net/SyslogAppender.html"><code>SyslogAppender</code></a>.
</p>
<p>Here are the properties you can pass to a SyslogAppender.</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="syslog">syslogHost</span></td>
<td><code>String</code></td>
<td>The host name of the syslog server.</td>
</tr>
<tr>
<td><span class="prop" container="syslog">port</span></td>
<td><code>String</code></td>
<td>The port number on the syslog server to connect
to. Normally, one would not want to change the default value
of <em>514</em>.
</td>
</tr>
<tr>
<td><span class="prop" container="syslog">facility</span></td>
<td><code>String</code></td>
<td>
<p>The <span class="prop">facility</span> is meant to identify
the source of a message.</p>
<p>The <span class="prop">facility</span> option must be set
to one of the strings <em>KERN, USER, MAIL, DAEMON, AUTH,
SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, NTP, AUDIT,
ALERT, CLOCK, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4,
LOCAL5, LOCAL6, LOCAL7</em>. Case is not important.</p>
</td>
</tr>
<tr>
<td><span class="prop" container="syslog">suffixPattern</span></td>
<td><code>String</code></td>
<td><p>The <span class="prop">suffixPattern</span> option
specifies the format of the non-standardized part of the
message sent to the syslog server. By default, its value is
<em>[%thread] %logger %msg</em>. Any value that a
<code>PatternLayout</code> could use is a correct <span
class="prop">suffixPattern</span> value.
</p>
</td>
</tr>
<tr>
<td><span class="prop"
container="syslog">stackTracePattern</span></td>
<td><code>String</code></td>
<td><p>The <span class="prop">stackTracePattern</span>
property allows the customization of the string appearing just
before each stack trace line. The default value for this
property is "\t", i.e. the tab character. Any value accepted
by <code>PatternLayout</code> is a valid value for <span
class="prop">stackTracePattern</span>.</p>
</td>
</tr>
<tr>
<td><span class="prop" container="syslog">throwableExcluded</span></td>
<td><code>boolean</code></td>
<td>Setting <span class="prop">throwableExcluded</span> to
<code>true</code> will cause stack trace data associated with
a Throwable to be omitted. By default, <span
class="prop">throwableExcluded</span> is set to
<code>false</code> so that stack trace data is sent to the
syslog server. </td>
</tr>
</table>
<p>The syslog severity of a logging event is converted from the
level of the logging event. The <em>DEBUG</em> level is converted
to <em>7</em>, <em>INFO</em> is converted to <em>6</em>,
<em>WARN</em> is converted to <em>4</em> and <em>ERROR</em> is
converted to <em>3</em>.
</p>
<p>Since the format of a syslog request follows rather strict
rules, there is no layout to be used with
<code>SyslogAppender</code>. However, using the <span
class="prop">suffixPattern</span> option lets the user display
whatever information she wishes.
</p>
<p>Here is a sample configuration using a
<code>SyslogAppender</code>.</p>
<p class="example">Example: <code>SyslogAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/conf/logback-syslog.xml)</p>
<span class="asGroovy" onclick="return asGroovy('logback-syslog');">View as .groovy</span>
<pre id="logback-syslog" class="prettyprint source"><configuration>
<appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>remote_home</syslogHost>
<facility>AUTH</facility>
<suffixPattern>[%thread] %logger %msg</suffixPattern>
</appender>
<root level="DEBUG">
<appender-ref ref="SYSLOG" />
</root>
</configuration></pre>
<p>When testing this configuration, you should verify that the
remote syslog daemon accepts requests from an external
source. Experience shows that, by default, syslog daemons usually
deny requests coming via a network connection.
</p>
<h3 class="doAnchor" name="SiftingAppender">SiftingAppender</h3>
<p>As its name implies, a <code>SiftingAppender</code> can be used
to separate (or sift) logging according to a given runtime
attribute. For example, <code>SiftingAppender</code> can separate
logging events according to user sessions, so that the logs
generated by different users go into distinct log files, one log
file per user.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="sift">timeout</span></td>
<td><code><a
href="../apidocs/ch/qos/logback/core/util/Duration.html">Duration</a></code></td>
<td>A nested appender which has not been accessed beyond the
<span class="prop">timeout</span> duration is deemed stale. A
stale appender is closed and unreferenced by
<code>SiftingAppender</code>. The default value for <span
class="prop">timeout</span> is 30 minutes.</td>
</tr>
<tr>
<td><span class="prop" container="sift">maxAppenderCount</span></td>
<td><code>integer</code></td>
<td>The maximum number of nested appenders
<code>SiftingAppender</code> may create and track. Default
value for <span class="prop">maxAppenderCount</span> is
Integer.MAX_VALUE.</td>
</tr>
</table>
<p><code>SiftingAppender</code> achieves this feat by creating
nested appenders on the fly. Nested appenders are created based on
a template specified within the configuration of the
<code>SiftingAppender</code> itself (enclosed within the
<code><sift></code> element, see example
below). <code>SiftingAppender</code> is responsible for managing
the lifecycle of child appenders. For example,
<code>SiftingAppender</code> will automatically close and remove
any stale appender. A nested appender is considered stale when no
accesses it beyond the duration specified by the <span
class="prop">timeout</span> parameter.
</p>
<p>When handling a logging event, <code>SiftingAppender</code>
will select a child appender to delegate to. The selection
criteria are computed at runtime by a discriminator. The user can
specify the selection criteria with the help of a <code><a
href="../xref/ch/qos/logback/core/sift/Discriminator.html">Discriminator</a></code>. Let
us now study an example.
</p>
<h4>Example</h4>
<p>The <a
href="../xref/chapters/appenders/sift/SiftExample.html">SiftExample</a>
application logs a message stating that the application has
started. It then sets the MDC key "userid" to "Alice" and logs a
message. Here is the salient code:</p>
<p class="source">logger.debug("Application started");
MDC.put("userid", "Alice");
logger.debug("Alice says hello"); </p>
<p>The template for the configuration file illustrates the use of
<code>SiftingAppender</code>.</p>
<p class="example">Example: <code>SiftingAppender</code>
configuration
(logback-examples/src/main/resources/chapters/appenders/sift/byUserid.xml)</p>
<span class="asGroovy" onclick="return asGroovy('byUserid');">View as .groovy</span>
<pre id="byUserid" class="prettyprint source"><configuration>
<b><appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"></b>
<!-- in the absence of the class attribute, it is assumed that the
desired discriminator type is
ch.qos.logback.classic.sift.MDCBasedDiscriminator -->
<b><discriminator></b>
<b><key><span class="green">userid</span></key></b>
<b><defaultValue>unknown</defaultValue></b>
<b></discriminator></b>
<b><sift></b>
<b><appender name="FILE-<span class="green">${userid}</span>" class="ch.qos.logback.core.FileAppender"></b>
<b><file><span class="green">${userid}</span>.log</file></b>
<b><append>false</append></b>
<b><layout class="ch.qos.logback.classic.PatternLayout"></b>
<b><pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern></b>
<b></layout></b>
<b></appender></b>
<b></sift></b>
</appender>
<root level="DEBUG">
<appender-ref ref="SIFT" />
</root>
</configuration></pre>
<p>In the absence of a class attribute, it is assumed that the
discriminator type is <a
href="../xref/ch/qos/logback/classic/sift/MDCBasedDiscriminator.html">MDCBasedDiscriminator</a>.
The discriminating value is the MDC value associated with the key
given by the <span class="prop">key</span> property. However, if
that MDC value is null, then <span
class="prop">defaultValue</span> is used as the discriminating
value.
</p>
<p>The <code>SiftingAppender</code> is unique in its capacity to
reference and configure child appenders. In the above example,
<code>SiftingAppender</code> will create multiple
<code>FileAppender</code> instances, each
<code>FileAppender</code> instance identified by the value
associated with the "userid" MDC key. Whenever the "userid" MDC
key is assigned a new value, a new <code>FileAppender</code>
instance will be built from scratch. The
<code>SiftingAppender</code> keeps track of the appenders it
creates. Appenders unused for 30 minutes will be automatically
closed and discarded.
</p>
<p><span class="label notice">Variable export</span> It is not
enough to have different appender instances; each instance must
output to a distinct target resource. To allow such
differentiation, within the appender template, the key passed to
the discriminator, "userid" in the above example, is exported and
becomes a <a
href="configuration.html#variableSubstitution">variable</a>. Consequently,
this variable can be used to differentiate the actual resource
used by a given child appender.
</p>
<p>Running the <code>SiftExample</code> application with the
"byUserid.xml" configuration file shown above, will result in two
distinct log files, "unknown.log" and "Alice.log".
</p>
<p><span class="label">local-scoped variables</span> As of version
1.0.12, properties defined in local scope within the configuration
file will be available to nested appenders. Moreover, you can <a
href="configuration.html#definingProps">define variables</a> or <a
href="configuration.html#definingPropsOnTheFly">dynamically
compute</a> variables from <em>within</em> the the
<code><sift></code> element. Combining a variable from parts
defined outside and within the <code><sift></code> element is
also supported.
</p>
<h4 class="doAnchor" name="siftGettingTimeoutRight">Getting the
<span class="prop">timeout</span> right</h4>
<p>For certain types of applications, it may be difficult to get
the <span class="prop">timeout</span> parameter right. If the
<span class="prop">timeout</span> is too small, a nested appender
might be removed just to be created anew a few seconds later. This
phenomenon is called <em>trashing</em>. If the <span
class="prop">timeout</span> is too long and appenders are created
in quick succession, you might run out of resources. Similarly,
setting <span class="prop">maxAppenderCount</span> too low might
cause trashing as well.
</p>
<p>In many case, it may be easier to pinpoint a location in your
code after which a nested appender is no longer needed. If such a
location exists, even approximately, log from that location using
the <a
href="../apidocs/ch/qos/logback/classic/ClassicConstants.html#FINALIZE_SESSION_MARKER">FINALIZE_SESSION</a>
marker. Whenever SiftingAppender sees a logging event marked as
<code>FINALIZE_SESSION</code> it will end-of-life the associated
nested appender. Upon reaching its end-of-life, a nested appender
will linger for a few seconds to process any late coming events
(if any) and then will be closed.
</p>
<pre class="prettyprint source">import org.slf4j.Logger;
import static ch.qos.logback.classic.ClassicConstants.FINALIZE_SESSION_MARKER;
void job(String jobId) {
MDC.put("jobId", jobId);
logger.info("Starting job.");
... do whather the job needs to do
// will cause the nested appender reach end-of-life. It will
// linger for a few seconds.
logger.info(FINALIZE_SESSION_MARKER, "About to end the job");
try {
.. perform clean up
} catch(Exception e);
// This log statement will be handled by the lingering appender.
// No new appender will be created.
logger.error("unexpected error while cleaning up", e);
}
}
</pre>
<h3 class="doAnchor" name="AsyncAppender">AsyncAppender</h3>
<p>AsyncAppender logs <a
href="../apidocs/ch/qos/logback/classic/spi/ILoggingEvent.html">ILoggingEvent</a>s
asynchronously. It acts solely as an event dispatcher and must
therefore reference another appender in order to do anything
useful.</p>
<p><span class="label notice">Lossy by default if 80% full</span>
AsyncAppender buffers events in a <a
href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html">
BlockingQueue</a>. A worker thread created by
<code>AsyncAppender</code> takes events from the head of the
queue, and dispatches them to the single appender attached to
<code>AsyncAppender</code>. Note that by default,
<code>AsyncAppender</code> will drop events of level TRACE, DEBUG
and INFO if its queue is 80% full. This strategy has an amazingly
favorable effect on performance at the cost of event loss.
</p>
<p><span class="label">Application stop/redeploy</span> Upon
application shutdown or redeploy, <code>AsyncAppender</code> must
be stopped in order to stop and reclaim the worker thread and to
flush the logging events from the queue. This can be achieved by
<a href="configuration.html#stopContext">stopping the
LoggerContext</a> which will close all appenders, including any
<code>AsyncAppender</code> instances. <code>AsyncAppender</code>
will wait for the worker thread to flush up to the timeout specified
in <span class="prop">maxFlushTime</span>. If you find that queued events
are being discarded during close of the <code>LoggerContext</code>, you
may need to increase the time out. Specifying a value of 0 for
<span class="prop">maxFlushTime</span> will force the <code>AsyncAppender</code>
to wait for all queued events to be flushed before returning from
the stop method.
</p>
<p><span class="label">Post shutdown cleanup</span>
Depending on the mode of JVM shutdown, the worker thread processing the
queued events can be interrupted causing events to be strandeds in the
queue. This generally occurs when the <code>LoggerContext</code> is not
stopped cleanly or when the JVM terminates outside of the typical control
flow. In order to avoid interrupting the worker thread under these
conditions, a shutdown hook can be inserted to the JVM runtime that
<a href="configuration.html#stopContext">stops the LoggerContext properly</a>
after JVM shutdown has been initiated. A shutdown hook may also be the
preferred method for cleanly shutting down Logback when other shutdown hooks
attempt to log events.
</p>
<p>Here is the list of properties admitted by
<code>AsyncAppender:</code></p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><span class="prop" container="async">queueSize</span></td>
<td><code>int</code></td>
<td>The maximum capacity of the blocking queue. By default,
<span class="prop">queueSize</span> is set to 256.
</td>
</tr>
<tr>
<td><span class="prop" container="async">discardingThreshold</span></td>
<td><code>int</code></td>
<td>By default, when the blocking queue has 20% capacity
remaining, it will drop events of level TRACE, DEBUG and INFO,
keeping only events of level WARN and ERROR. To keep all
events, set <span class="prop">discardingThreshold</span> to
0.
</td>
</tr>
<tr>
<td><span class="prop" container="async">includeCallerData</span></td>
<td><code>boolean</code></td>
<td>Extracting caller data can be rather expensive. To improve
performance, by default, caller data associated with an event
is not extracted when the event added to the event queue. By
default, only "cheap" data like the thread name and the <a
href="mdc.html">MDC</a> are copied. You can direct this
appender to include caller data by setting the <span
class="prop">includeCallerData</span> property to true.
</td>
</tr>
<tr>
<td><span class="prop" container="async">maxFlushTime</span></td>
<td><code>int</code></td>
<td>Depending on the queue depth and latency to the referenced appender,
the <code>AsyncAppender</code> may take an unacceptable amount of
time to fully flush the queue. When the <code>LoggerContext</code> is
stopped, the <code>AsyncAppender stop</code> method waits
up to this timeout for the worker thread to complete. Use
<span class="prop">maxFlushTime</span> to specify a maximum queue flush
timeout in milliseconds. Events that cannot be processed within this
window are discarded. Semantics of this value are identical to that of
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join(long)">Thread.join(long)</a>.
</td>
</tr>
<tr>
<td><span class="prop" container="async">neverBlock</span></td>
<td><code>boolean</code></td>
<td>If <code>false</code> (the default) the appender will block on
appending to a full queue rather than losing the message. Set to
<code>true</code> and the appender will just drop the message and
will not block your application.</td>
</tr>
</table>
<p>By default, event queue is configured with a maximum capacity
of 256 events. If the queue is filled up, then application
threads are blocked from logging new events until the worker
thread has had a chance to dispatch one or more events. When the
queue is no longer at its maximum capacity, application threads
are able to start logging events once again. Asynchronous logging
therefore becomes pseudo-synchronous when the appender is
operating at or near the capacity of its event buffer. This is not
necessarily a bad thing. The appender is designed to allow the
application to keep on running, albeit taking slightly more time
to log events until the pressure on the appenders buffer eases.
</p>
<p>Optimally tuning the size of the appenders event queue for
maximum application throughput depends upon several factors. Any
or all of the following factors are likely to cause
pseudo-synchronous behavior to be exhibited:</p>
<ul>
<li>Large numbers of application threads</li>
<li>Large numbers of logging events per application call</li>
<li>Large amounts of data per logging event</li>
<li>High latency of child appenders</li>
</ul>
<p>To keep things moving, increasing the size of the queue will
generally help, at the expense of heap available to the
application.
</p>
<p><span class="label notice">Lossy behavior</span> In light of
the discussion above and in order to reduce blocking, by default,
when less than 20% of the queue capacity remains,
<code>AsyncAppender</code> will drop events of level TRACE, DEBUG
and INFO keeping only events of level WARN and ERROR. This
strategy ensures non-blocking handling of logging events (hence
excellent performance) at the cost loosing events of level TRACE,
DEBUG and INFO when the queue has less than 20% capacity. Event
loss can be prevented by setting the <span
class="prop">discardingThreshold</span> property to 0 (zero).
</p>
<p class="example">Example: <code>AsyncAppender</code>
configuration
(logback-examples/src/main/resources/chapters/appenders/conc/logback-async.xml)</p>
<span class="asGroovy" onclick="return asGroovy('asyncAppender');">View as .groovy</span>
<pre id="asyncAppender" class="prettyprint source"><configuration>
<appender name="<b>FILE</b>" class="ch.qos.logback.core.FileAppender">
<file>myapp.log</file>
<encoder>
<pattern>%logger{35} - %msg%n</pattern>
</encoder>
</appender>
<b><appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"></b>
<b><appender-ref ref="FILE" /></b>
<b></appender></b>
<root level="DEBUG">
<appender-ref ref="<b>ASYNC</b>" />
</root>
</configuration></pre>
<h3 class="doAnchor" name="WriteYourOwnAppender">Writing your own
Appender</h3>
<p>You can easily write your appender by subclassing
<code>AppenderBase</code>. It handles support for filters, status
messages and other functionality shared by most appenders. The
derived class only needs to implement one method, namely
<code>append(Object eventObject)</code>.
</p>
<p>The <code>CountingConsoleAppender</code>, which we list next,
appends a limited number of incoming events on the console. It
shuts down after the limit is reached. It uses a
<code>PatternLayoutEncoder</code> to format the events and accepts
a parameter named <code>limit</code>. Therefore, a few more
methods beyond <code>append(Object eventObject)</code> are
needed. As shown below, these parameters are handles
auto-magically by logback's various configuration mechanisms.
</p>
<em>Example 4.<span class="autoExec"/>:
<code>CountingConsoleAppender</code>
(logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java)</em>
<pre class="prettyprint source">package chapters.appenders;
import java.io.IOException;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
public class CountingConsoleAppender extends AppenderBase<ILoggingEvent> {
static int DEFAULT_LIMIT = 10;
int counter = 0;
int limit = DEFAULT_LIMIT;
PatternLayoutEncoder encoder;
public void setLimit(int limit) {
this.limit = limit;
}
public int getLimit() {
return limit;
}
@Override
public void start() {
if (this.encoder == null) {
addError("No encoder set for the appender named ["+ name +"].");
return;
}
try {
encoder.init(System.out);
} catch (IOException e) {
}
super.start();
}
public void append(ILoggingEvent event) {
if (counter >= limit) {
return;
}
// output the events as formatted by our layout
try {
this.encoder.doEncode(event);
} catch (IOException e) {
}
// prepare for next event
counter++;
}
public PatternLayoutEncoder getEncoder() {
return encoder;
}
public void setEncoder(PatternLayoutEncoder encoder) {
this.encoder = encoder;
}
}</pre>
<p>The <code>start()</code> method checks for the presence of a
<code>PatternLayoutEncoder</code>. In case the encoder is not
set, the appender fails to start and emits an error message.
</p>
<p>This custom appender illustrates two points:</p>
<ul>
<li>All properties that follow the setter/getter JavaBeans
conventions are handled transparently by logback
configurators. The <code>start()</code> method, which is called
automatically during logback configuration, has the
responsibility of verifying that the various properties of the
appender are set and are coherent.
</li>
<li>The <code>AppenderBase.doAppend()</code> method invokes the
append() method of its derived classes. Actual output
operations occur in the <code>append</code>() method. In
particular, it is in this method that appenders format events by
invoking their layouts.
</li>
</ul>
<p>The <a
href="../xref/chapters/appenders/CountingConsoleAppender.html"><code>CountingConsoleAppender</code></a>
can be configured like any other appender. See sample
configuration file
<em>logback-examples/src/main/resources/chapters/appenders/countingConsole.xml</em>
for an example.
</p>
<h2 class="doAnchor" name="logback_access">Logback Access</h2>
<p>Most of the appenders found in logback-classic have their
equivalent in logback-access. These work essentially in the same
way as their logback-classic counterparts. In the next section, we
will cover their use.
</p>
<h3 class="doAnchor" name="AccessSocketAppender">SocketAppender
and SSLSocketAppender</h3>
<p>The <a
href="../xref/ch/qos/logback/access/net/SocketAppender.html">
<code>SocketAppender</code></a> is designed to log to a remote
entity by transmitting serialized <code>AccessEvent</code> objects
over the wire. Remote logging is non-intrusive as far as the
access event is concerned. On the receiving end after
deserialization, the event can be logged as if it were generated
locally.
</p>
<p>The <a href="../xref/ch/qos/logback/access/net/SSLSocketAppender.html">
<code>SSLSocketAppender</code></a> extends the basic
<code>SocketAppender</code> allowing logging to a remote entity over
the Secure Sockets Layer (SSL).
</p>
<p>
The properties of access' <code>SocketAppender</code> are the same as those available
for classic's <code>SocketAppender</code>.
</p>
<h3 class="doAnchor"
name="AccessServerSocketAppender">ServerSocketAppender and
SSLServerSocketAppender</h3>
<p>Like <code>SocketAppender</code>, the <a
href="../xref/ch/qos/logback/access/net/server/ServerSocketAppender.html">
<code>ServerSocketAppender</code></a> is designed to log to a remote
entity by transmitting serialized <code>AccessEvent</code> objects
over the wire. However, when using <code>ServerSocketAppender</code>
the appender acts as a server, passively listening on a TCP socket awaiting
inbound connections from interested clients. Logging events delivered
to the appender are distributed to all connected clients.
</p>
<p>The <a href="../xref/ch/qos/logback/access/net/server/SSLServerSocketAppender.html">
<code>SSLSocketAppender</code></a> extends the basic
<code>ServerSocketAppender</code> allowing logging to a remote entity
over the Secure Sockets Layer (SSL).
</p>
<p>The properties of access' <code>ServerSocketAppender</code> are
the same as those available for classic's
<code>ServerSocketAppender</code>.
</p>
<h3 class="doAnchor" name="AccessSMTPAppender">SMTPAppender</h3>
<p>Access' <a
href="../xref/ch/qos/logback/access/net/SMTPAppender.html">
<code>SMTPAppender</code></a> works in the same way as its Classic
counterpart. However, the <span class="prop">evaluator</span>
option is rather different. By default, a
<code>URLEvaluator</code> object is used by
<code>SMTPAppender</code>. This evaluator contains a list of URLs
that are checked against the current request's URL. When one of
the pages given to the <code>URLEvaluator</code> is requested,
<code>SMTPAppender</code> sends an email.
</p>
<p>
Here is a sample configuration of a <code>SMTPAppender</code> in the access environment.
</p>
<p class="example">Example: <code>SMTPAppender</code>
configuration
(logback-examples/src/main/resources/chapters/appenders/conf/access/logback-smtp.xml)</p>
<pre class="prettyprint source"><appender name="SMTP"
class="ch.qos.logback.access.net.SMTPAppender">
<layout class="ch.qos.logback.access.html.HTMLLayout">
<pattern>%h%l%u%t%r%s%b</pattern>
</layout>
<b><Evaluator class="ch.qos.logback.access.net.URLEvaluator">
<URL>url1.jsp</URL>
<URL>directory/url2.html</URL>
</Evaluator></b>
<from>sender_email@host.com</from>
<smtpHost>mail.domain.com</smtpHost>
<to>recipient_email@host.com</to>
</appender></pre>
<p>This way of triggering the email lets users select pages that
are important steps in a specific process, for example. When such
a page is accessed, the email is sent with the pages that were
accessed previously, and any information the user wants to be
included in the email.
</p>
<h3 class="doAnchor" name="AccessDBAppender">DBAppender</h3>
<p><a
href="../xref/ch/qos/logback/access/db/DBAppender.html"><code>DBAppender</code></a>
is used to insert the access events into a database.
</p>
<p>Two tables are used by <code>DBAppender</code>:
<em>access_event</em> and <em>access_event_header</em>. They both
must exist before <code>DBAppender</code> can be used. Logback
ships with SQL scripts that will create the tables. They can be
found in the
<em>logback-access/src/main/java/ch/qos/logback/access/db/script</em>
directory. There is a specific script for each of the most popular
database systems. If the script for your particular type of
database system is missing, it should be quite easy to write one,
taking as example one of the existing scripts. You are encouraged
to contribute such missing scripts back to the project.
</p>
<p>The <em>access_event</em> table's fields are described below:</p>
<table class="bodyTable striped">
<tr>
<th>Field</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><b>timestamp</b></td>
<td><code>big int</code></td>
<td>The timestamp that was valid at the access event's creation.</td>
</tr>
<tr>
<td><b>requestURI</b></td>
<td><code>varchar</code></td>
<td>The URI that was requested.</td>
</tr>
<tr>
<td><b>requestURL</b></td>
<td><code>varchar</code></td>
<td>The URL that was requested. This is a string composed of the request method,
the request URI and the request protocol.
</td>
</tr>
<tr>
<td><b>remoteHost</b></td>
<td><code>varchar</code></td>
<td>The name of the remote host.</td>
</tr>
<tr>
<td><b>remoteUser</b></td>
<td><code>varchar</code></td>
<td>
The name of the remote user.
</td>
</tr>
<tr>
<td><b>remoteAddr</b></td>
<td><code>varchar</code></td>
<td>The remote IP address.</td>
</tr>
<tr>
<td><b>protocol</b></td>
<td><code>varchar</code></td>
<td>The request protocol, like <em>HTTP</em> or <em>HTTPS</em>.</td>
</tr>
<tr>
<td><b>method</b></td>
<td><code>varchar</code></td>
<td>The request method, usually <em>GET</em> or <em>POST</em>.</td>
</tr>
<tr>
<td><b>serverName</b></td>
<td><code>varchar</code></td>
<td>The name of the server that issued the request.</td>
</tr>
<tr>
<td><b>event_id</b></td>
<td><code>int</code></td>
<td>The database id of the access event.</td>
</tr>
</table>
<p>
The <em>access_event_header</em> table contains the header of each
request. The information is organised as shown below:
</p>
<table class="bodyTable striped">
<tr>
<th>Field</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td><b>event_id</b></td>
<td><code>int</code></td>
<td>The database id of the corresponding access event.</td>
</tr>
<tr>
<td><b>header_key</b></td>
<td><code>varchar</code></td>
<td>The header name, for example <em>User-Agent</em>.</td>
</tr>
<tr>
<td><b>header_value</b></td>
<td><code>varchar</code></td>
<td>The header value, for example <em>Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0</em></td>
</tr>
</table>
<p>All properties of classic's <code>DBAppender</code> are available
in access's <code>DBAppender</code>. The latter offers one more option,
described below.
</p>
<table class="bodyTable striped">
<tr>
<th>Property Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td>
<b>
<span class="prop">insertHeaders</span>
</b>
</td>
<td>
<code>boolean</code>
</td>
<td>
Tells the <code>DBAppender</code> to populate the database with the header
information of all incoming requests.
</td>
</tr>
</table>
<p>Here is a sample configuration that uses <code>DBAppender</code>.</p>
<p class="example">Example: DBAppender configuration <em>(logback-examples/src/main/resources/chapters/appenders/conf/access/logback-DB.xml)</em></p>
<pre class="prettyprint source"><configuration>
<appender name="DB" class="ch.qos.logback.access.db.DBAppender">
<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:3306/logbackdb</url>
<user>logback</user>
<password>logback</password>
</connectionSource>
<insertHeaders>true</insertHeaders>
</appender>
<appender-ref ref="DB" />
</configuration></pre>
<h3 class="doAnchor"
name="AccessSiftingAppender">SiftingAppender</h3>
<p>The SiftingAppender in logback-access is quite similar to its
logback-classic counterpart. The main difference is that in
logback-access the default discriminator, namely <a
href="../xref/ch/qos/logback/access/sift/AccessEventDiscriminator.html">AccessEventDiscriminator</a>,
is not MDC based. As its name suggests, AccessEventDiscriminator,
uses a designated field in AccessEvent as the basis for selecting a
nested appender. If the value of the designated field is null,
then the value specified in the <span
class="prop">defaultValue</span> property is used.
</p>
<p>The designated AccessEvent field can be one of COOKIE,
REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, LOCAL_PORT,
REQUEST_URI. Note that the first three fields require that the
<span class="prop">AdditionalKey</span> property also be
specified.</p>
<p>Below is an example configuration file.</p>
<p class="example">Example: SiftingAppender configuration (logback-examples/src/main/resources/chapters/appenders/conf/sift/access-siftingFile.xml)</p>
<pre class="prettyprint source"><configuration>
<appender name="SIFTING" class="ch.qos.logback.access.sift.SiftingAppender">
<Discriminator class="ch.qos.logback.access.sift.AccessEventDiscriminator">
<Key>id</Key>
<FieldName>SESSION_ATTRIBUTE</FieldName>
<AdditionalKey>username</AdditionalKey>
<defaultValue>NA</defaultValue>
</Discriminator>
<sift>
<appender name="ch.qos.logback:logback-site:jar:1.2.3" class="ch.qos.logback.core.FileAppender">
<file>byUser/ch.qos.logback:logback-site:jar:1.2.3.log</file>
<layout class="ch.qos.logback.access.PatternLayout">
<pattern>%h %l %u %t \"%r\" %s %b</pattern>
</layout>
</appender>
</sift>
</appender>
<appender-ref ref="SIFTING" />
</configuration></pre>
<p>In the above configuration file, a <code>SiftingAppender</code>
nests <code>FileAppender</code> instances. The key "id" is
designated as a variable which will be available to the nested
<code>FileAppender</code> instances. The default discriminator,
namely <code>AccessEventDiscriminator</code>, will search for a
"username" session attribute in each <code>AccessEvent</code>. If
no such attribute is available, then the default value "NA" will
be used. Thus, assuming the session attribute named "username"
contains the username of each logged on user, there will be a log
file under the <em>byUser/</em> folder (of the current folder)
named after each user containing the access logs for that user.
</p>
<script src="../templates/footer.js" type="text/javascript"></script>
</div>
</body>
</html>
|