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
|
> !! This document applies to the next version under development.
>
> See [here for documentation on the latest released version](https://github.com/logfellow/logstash-logback-encoder/tree/logstash-logback-encoder-7.2).
# Logstash Logback Encoder
[](https://github.com/logfellow/logstash-logback-encoder/actions)
[](http://www.javadoc.io/doc/net.logstash.logback/logstash-logback-encoder)
[](https://search.maven.org/artifact/net.logstash.logback/logstash-logback-encoder)
[](https://github.com/logfellow/logstash-logback-encoder/releases/latest)
Provides [logback](http://logback.qos.ch/) encoders, layouts, and appenders to log in JSON and [other formats supported by Jackson](#data-format).
Supports both regular _LoggingEvents_ (logged through a `Logger`) and _AccessEvents_ (logged via [logback-access](http://logback.qos.ch/access.html)).
Originally written to support output in [logstash](https://www.elastic.co/guide/en/logstash/current)'s JSON format, but has evolved into a highly-configurable, general-purpose, structured logging mechanism for JSON and other Jackson dataformats.
The structure of the output, and the data it contains, is fully configurable.
#### Contents:
* [Including it in your project](#including-it-in-your-project)
* [Java Version Requirements](#java-version-requirements)
* [Usage](#usage)
* [UDP Appender](#udp-appender)
* [TCP Appenders](#tcp-appenders)
* [Keep-alive](#keep-alive)
* [Multiple Destinations](#multiple-destinations)
* [Reconnection Delay](#reconnection-delay)
* [Connection Timeout](#connection-timeout)
* [Write Buffer Size](#write-buffer-size)
* [Write Timeouts](#write-timeouts)
* [SSL](#ssl)
* [Async Appenders](#async-appenders)
* [RingBuffer Full](#ringbuffer-full)
* [Graceful Shutdown](#graceful-shutdown)
* [Wait Strategy](#wait-strategy)
* [Appender Listeners](#appender-listeners)
* [Encoders / Layouts](#encoders--layouts)
* [LoggingEvent Fields](#loggingevent-fields)
* [Standard Fields](#standard-fields)
* [MDC fields](#mdc-fields)
* [Context fields](#context-fields)
* [Caller Info Fields](#caller-info-fields)
* [Custom Fields](#custom-fields)
* [Global Custom Fields](#global-custom-fields)
* [Event-specific Custom Fields](#event-specific-custom-fields)
* [AccessEvent Fields](#accessevent-fields)
* [Standard Fields](#standard-fields-1)
* [Header Fields](#header-fields)
* [Customizing Jackson](#customizing-jackson)
* [Data Format](#data-format)
* [Customizing JSON Factory and Generator](#customizing-json-factory-and-generator)
* [Registering Jackson Modules](#registering-jackson-modules)
* [Customizing Character Escapes](#customizing-character-escapes)
* [Masking](#masking)
* [Customizing Standard Field Names](#customizing-standard-field-names)
* [Customizing Version](#customizing-version)
* [Customizing Timestamp](#customizing-timestamp)
* [Customizing LoggingEvent Message](#customizing-loggingevent-message)
* [Customizing AccessEvent Message](#customizing-accessevent-message)
* [Customizing Logger Name Length](#customizing-logger-name-length)
* [Customizing Stack Traces](#customizing-stack-traces)
* [Prefix/Suffix/Separator](#prefixsuffixseparator)
* [Composite Encoder/Layout](#composite-encoderlayout)
* [Providers common to LoggingEvents and AccessEvents](#providers-common-to-loggingevents-and-accessevents)
* [Providers for LoggingEvents](#providers-for-loggingevents)
* [Providers for AccessEvents](#providers-for-accessevents)
* [Nested JSON Provider](#nested-json-provider)
* [Pattern JSON Provider](#pattern-json-provider)
* [LoggingEvent patterns](#loggingevent-patterns)
* [AccessEvent patterns](#accessevent-patterns)
* [Custom JSON Provider](#custom-json-provider)
* [Status Listeners](#status-listeners)
* [Joran/XML Configuration](#joran-xml-configuration)
* [Duration Property](#duration-property)
## Including it in your project
Maven style:
```xml
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>7.2</version>
<!-- Use runtime scope if the project does not have any compile-time usage of logstash-logback-encoder,
such as usage of StructuredArguments/Markers or implementations such as
JsonProvider, AppenderListener, JsonFactoryDecorator, JsonGeneratorDecorator, etc
<scope>runtime</scope>
-->
</dependency>
<!-- Your project must also directly depend on either logback-classic or logback-access. For example: -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
<!-- Use runtime scope if the project does not have any compile-time usage of logback,
such as implementations of Appender, Encoder, Layout, TurboFilter, etc
<scope>runtime</scope>
-->
</dependency>
```
If you get `ClassNotFoundException`/`NoClassDefFoundError`/`NoSuchMethodError` at runtime,
then ensure the required dependencies (and appropriate versions) as specified in the pom file
from the maven repository exist on the runtime classpath.
Specifically, the following need to be available on the runtime classpath:
* jackson-databind / jackson-core / jackson-annotations >= 2.12.0
* logback-core >= 1.2.0
* logback-classic >= 1.2.0 (required for logging _LoggingEvents_)
* logback-access >= 1.2.0 (required for logging _AccessEvents_)
* slf4j-api
* java-uuid-generator (required if the `uuid` provider is used)
Older versions than the ones specified in the pom file _might_ work, but the versions in the pom file are what testing has been performed against.
Support for logback versions prior to 1.2.0 was removed in logstash-logback-encoder 7.0.
If you are using logstash-logback-encoder in a project (such as spring-boot) that also declares dependencies on any of the above libraries, you might need to tell maven explicitly which versions to use to avoid conflicts.
You can do so using maven's [dependencyManagement](https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management) feature.
For example, to ensure that maven doesn't pick different versions of logback-core, logback-classic, and logback-access, add this to your project's pom.xml
```xml
<properties>
<logback.version>1.2.6</logback.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
```
## Java Version Requirements
| logstash-logback-encoder | Minimum Java Version supported |
| ------------------------ | -------------------------------|
| >= 6.0 | 1.8 |
| 5.x | 1.7 |
| <= 4.x | 1.6 |
## Usage
To log using JSON format, you must configure logback to use either:
* an appender provided by the logstash-logback-encoder library, OR
* an appender provided by logback (or another library) with an encoder or layout provided by the logstash-logback-encoder library
The appenders, encoders, and layouts provided by the logstash-logback-encoder library are as follows:
| Format | Protocol | Function | LoggingEvent | AccessEvent
|---------------|------------|----------| ------------ | -----------
| Logstash JSON | Syslog/UDP | Appender | [`LogstashUdpSocketAppender`](/src/main/java/net/logstash/logback/appender/LogstashUdpSocketAppender.java) | [`LogstashAccessUdpSocketAppender`](/src/main/java/net/logstash/logback/appender/LogstashAccessUdpSocketAppender.java)
| Logstash JSON | TCP | Appender | [`LogstashTcpSocketAppender`](/src/main/java/net/logstash/logback/appender/LogstashTcpSocketAppender.java) | [`LogstashAccessTcpSocketAppender`](/src/main/java/net/logstash/logback/appender/LogstashAccessTcpSocketAppender.java)
| any | any | Appender | [`LoggingEventAsyncDisruptorAppender`](/src/main/java/net/logstash/logback/appender/LoggingEventAsyncDisruptorAppender.java) | [`AccessEventAsyncDisruptorAppender`](/src/main/java/net/logstash/logback/appender/AccessEventAsyncDisruptorAppender.java)
| Logstash JSON | any | Encoder | [`LogstashEncoder`](/src/main/java/net/logstash/logback/encoder/LogstashEncoder.java) | [`LogstashAccessEncoder`](/src/main/java/net/logstash/logback/encoder/LogstashAccessEncoder.java)
| Logstash JSON | any | Layout | [`LogstashLayout`](/src/main/java/net/logstash/logback/layout/LogstashLayout.java) | [`LogstashAccessLayout`](/src/main/java/net/logstash/logback/layout/LogstashAccessLayout.java)
| General JSON | any | Encoder | [`LoggingEventCompositeJsonEncoder`](/src/main/java/net/logstash/logback/encoder/LoggingEventCompositeJsonEncoder.java) | [`AccessEventCompositeJsonEncoder`](/src/main/java/net/logstash/logback/encoder/AccessEventCompositeJsonEncoder.java)
| General JSON | any | Layout | [`LoggingEventCompositeJsonLayout`](/src/main/java/net/logstash/logback/layout/LoggingEventCompositeJsonLayout.java) | [`AccessEventCompositeJsonLayout`](/src/main/java/net/logstash/logback/encoder/AccessEventCompositeJsonLayout.java)
These encoders/layouts can generally be used by any logback appender (such as `RollingFileAppender`).
The general _composite_ JSON encoders/layouts can be used to
output any JSON format/data by configuring them with various JSON _providers_.
The Logstash encoders/layouts are really just extensions of the general
composite JSON encoders/layouts with a pre-defined set of providers.
The logstash encoders/layouts are easier to configure if you want to use the standard logstash version 1 output format.
Use the [composite encoders/layouts](#composite-encoderlayout) if you want to heavily customize the output,
or if you need to use logstash version 0 output.
The `*AsyncDisruptorAppender` appenders are similar to logback's `AsyncAppender`,
except that a [LMAX Disruptor RingBuffer](https://lmax-exchange.github.io/disruptor/)
is used as the queuing mechanism, as opposed to a `BlockingQueue`.
These async appenders can delegate to any other underlying logback appender.
### UDP Appender
To output JSON for LoggingEvents to a syslog/UDP channel,
use the `LogstashUdpSocketAppender` with a `LogstashLayout` or `LoggingEventCompositeJsonLayout`
in your `logback.xml`, like this:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
<host>MyAwesomeSyslogServer</host>
<!-- port is optional (default value shown) -->
<port>514</port>
<!-- layout is required -->
<layout class="net.logstash.logback.layout.LogstashLayout"/>
</appender>
<root level="all">
<appender-ref ref="stash" />
</root>
</configuration>
```
You can further customize the JSON output by customizing the layout as described in later sections.
For example, to configure [global custom fields](#global-custom-fields), you can specify
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
<host>MyAwesomeSyslogServer</host>
<!-- port is optional (default value shown) -->
<port>514</port>
<layout class="net.logstash.logback.layout.LogstashLayout">
<customFields>{"appname":"myWebservice"}</customFields>
</layout>
</appender>
```
To output JSON for AccessEvents over UDP, use a `LogstashAccessUdpSocketAppender`
with a `LogstashAccessLayout` or `AccessEventCompositeJsonLayout`
in your `logback-access.xml`, like this:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stash" class="net.logstash.logback.appender.LogstashAccessUdpSocketAppender">
<host>MyAwesomeSyslogServer</host>
<!-- port is optional (default value shown) -->
<port>514</port>
<layout class="net.logstash.logback.layout.LogstashAccessLayout">
<customFields>{"appname":"myWebservice"}</customFields>
</layout>
</appender>
<appender-ref ref="stash" />
</configuration>
```
To receive syslog/UDP input in logstash, configure a [`syslog`](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-syslog.html) or [`udp`](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-udp.html) input with the [`json`](https://www.elastic.co/guide/en/logstash/current/plugins-codecs-json.html) codec in logstash's configuration like this:
```
input {
syslog {
codec => "json"
}
}
```
### TCP Appenders
To output JSON for LoggingEvents over TCP, use a `LogstashTcpSocketAppender`
with a `LogstashEncoder` or `LoggingEventCompositeJsonEncoder`
in your `logback.xml`, like this:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>127.0.0.1:4560</destination>
<!-- encoder is required -->
<encoder class="net.logstash.logback.encoder.LogstashEncoder" />
</appender>
<root level="DEBUG">
<appender-ref ref="stash" />
</root>
</configuration>
```
To output JSON for AccessEvents over TCP, use a `LogstashAccessTcpSocketAppender`
with a `LogstashAccessEncoder` or `AccessEventCompositeJsonEncoder`
in your `logback-access.xml`, like this:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stash" class="net.logstash.logback.appender.LogstashAccessTcpSocketAppender">
<destination>127.0.0.1:4560</destination>
<!-- encoder is required -->
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder" />
</appender>
<appender-ref ref="stash" />
</configuration>
```
The TCP appenders use an encoder, rather than a layout as the [UDP appenders](#udp) .
You can use a `Logstash*Encoder`, `*EventCompositeJsonEncoder`, or any other logback encoder.
All of the output formatting options are configured at the encoder level.
Internally, the TCP appenders are asynchronous (using the [LMAX Disruptor RingBuffer](https://lmax-exchange.github.io/disruptor/)).
All the encoding and TCP communication is delegated to a single writer thread.
There is no need to wrap the TCP appenders with another asynchronous appender
(such as `AsyncAppender` or `LoggingEventAsyncDisruptorAppender`).
All the configuration parameters (except for sub-appender) of the [async appenders](#async)
are valid for TCP appenders. For example, `waitStrategyType` and `ringBufferSize`.
The TCP appenders will never block the logging thread.
If the RingBuffer is full (e.g. due to slow network, etc), then events will be dropped.
The TCP appenders will automatically reconnect if the connection breaks.
However, events may be lost before Java's socket realizes the connection has broken.
To receive TCP input in logstash, configure a [`tcp`](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-tcp.html) input with the [`json_lines`](https://www.elastic.co/guide/en/logstash/current/plugins-codecs-json_lines.html) codec in logstash's configuration like this:
```
input {
tcp {
port => 4560
codec => json_lines
}
}
```
In order to guarantee that logged messages have had a chance to be processed by the TCP appender, you'll need to [cleanly shut down logback](http://logback.qos.ch/manual/configuration.html#stopContext) when your application exits.
#### Keep-Alive
If events occur infrequently, and the connection breaks consistently due to a server-side idle timeout,
then you can enable keep alive functionality by configuring a `keepAliveDuration` like this:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
...
<keepAliveDuration>5 minutes</keepAliveDuration>
</appender>
```
This setting accepts a Logback Duration value - see the section dedicated to [Duration Property](#duration-property) for more information about the valid values.
When the `keepAliveDuration` is set, then a keep alive message will be sent if an event has not occurred for the length of the duration.
The keep alive message defaults to unix line ending (`\n`), but can be changed by setting the `keepAliveMessage` property to the desired value. The following values have special meaning:
- `<empty string>`: no keep alive
- `SYSTEM`: system's line separator
- `UNIX`: unix line ending (`\n`)
- `WINDOWS`: windows line ending (`\r\n`)
Any other value will be used as-is.
The keep alive message is encoded in `UTF-8` by default. This can be changed by setting the `keepAliveCharset` property to the name of the desired charset.
#### Multiple Destinations
The TCP appenders can be configured to try to connect to one of several destinations like this:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>destination1.domain.com:4560</destination>
<destination>destination2.domain.com:4560</destination>
<destination>destination3.domain.com:4560</destination>
...
</appender>
```
or this:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>
destination1.domain.com:4560,
destination2.domain.com:4560,
destination3.domain.com:4560
</destination>
...
</appender>
```
The appender uses a `connectionStrategy` to determine:
* the order in which destination connections are attempted, and
* when an established connection should be reestablished (to the next destination selected by the connection strategy).
Logs are only sent to one destination at a time (i.e. not all destinations).
By default, the appender will stay connected to the connected destination
until it breaks, or until the application is shut down.
Some connection strategies can force a reconnect (see below).
If a connection breaks, then the appender will attempt to connect
to the next destination selected by the connection strategy.
The available connection strategies are as follows:
<table>
<tbody>
<tr>
<th>Strategy</th>
<th>Description</th>
</tr>
<tr>
<td valign="top"><tt>preferPrimary</tt></td>
<td>(default)
The first destination is considered the <em>primary</em> destination.
Each additional destination is considered a <em>secondary</em> destination.
This strategy prefers the primary destination, unless it is down.
The appender will attempt to connect to each destination in the order in which they are configured.
If a connection attempt fails, thes the appender will attempt to connect to the next destination.
If a connection succeeds, and then closes <em>before</em> the <tt>minConnectionTimeBeforePrimary</tt>
has elapsed, then the appender will attempt to connect to the next destination.
If a connection succeeds, and then closes <em>after</em> the <tt>minConnectionTimeBeforePrimary</tt>
has elapsed, then the appender will attempt to connect
to the destinations in the order in which they are configured,
starting at the first/primary destination.
<br/><br/>
The <tt>secondaryConnectionTTL</tt> can be set to gracefully close connections to <em>secondary</em>
destinations after a specific duration. This will force the
the appender to reattempt to connect to the destinations in order again.
The <tt>secondaryConnectionTTL</tt> value does not affect connections to the
<em>primary</em> destination.
<br/><br/>
The <tt>minConnectionTimeBeforePrimary</tt> (10 seconds by default) specifies
the minimum amount of time that a sucessfully established connection
must remain open before the next connection attempt will try the primary.
i.e. If a connection stays open less than this amount of time,
then the next connection attempt will attempt the next destination (instead of the primary).
This is used to prevent a connection storm to the primary in the case the
primary accepts a connection, and then immediately closes it.
<br/><br/>
Example:
<pre>
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>destination1.domain.com:4560</destination>
<destination>destination2.domain.com:4560</destination>
<destination>destination3.domain.com:4560</destination>
<connectionStrategy>
<preferPrimary>
<secondaryConnectionTTL>5 minutes</secondaryConnectionTTL>
</preferPrimary>
</connectionStrategy>
</appender>
</pre>
</td>
</tr>
<tr>
<td valign="top"><tt>roundRobin</tt></td>
<td>
This strategy attempts connections to the destination in round robin order.
If a connection fails, the next destination is attempted.
<br/><br/>
The <tt>connectionTTL</tt> can be set to gracefully close connections after a specific duration.
This will force the the appender to reattempt to connect to the next destination.
<br/><br/>
Example:
<pre>
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>destination1.domain.com:4560</destination>
<destination>destination2.domain.com:4560</destination>
<destination>destination3.domain.com:4560</destination>
<connectionStrategy>
<roundRobin>
<connectionTTL>5 minutes</connectionTTL>
</roundRobin>
</connectionStrategy>
</appender>
</pre>
</td>
</tr>
<tr>
<td valign="top"><tt>random</tt></td>
<td>
This strategy attempts connections to the destination in a random order.
If a connection fails, the next random destination is attempted.
<br/><br/>
The <tt>connectionTTL</tt> can be set to gracefully close connections after a specific duration.
This will force the the appender to reattempt to connect to the next random destination.
<br/><br/>
Example:
<pre>
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>destination1.domain.com:4560</destination>
<destination>destination2.domain.com:4560</destination>
<destination>destination3.domain.com:4560</destination>
<connectionStrategy>
<random>
<connectionTTL>5 minutes</connectionTTL>
</random>
</connectionStrategy>
</appender>
</pre>
</td>
</tr>
</tbody>
</table>
You can also use your own custom connection strategy by implementing the `DestinationConnectionStrategy` interface,
and configuring the appender to use it like this:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>destination1.domain.com:4560</destination>
<destination>destination2.domain.com:4560</destination>
<destination>destination3.domain.com:4560</destination>
<connectionStrategy class="your.package.YourDestinationConnectionStrategy">
</connectionStrategy>
</appender>
```
#### Reconnection Delay
By default, the TCP appender will wait 30 seconds between connection attempts to a single destination.
The time between connection attempts to each destination is tracked separately.
This amount of time to delay can be changed by setting the `reconnectionDelay` field.
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
...
<reconnectionDelay>1 second</reconnectionDelay>
</appender>
```
This setting accepts a Logback Duration value - see the section dedicated to [Duration Property](#duration-property) for more information about the valid values.
#### Connection Timeout
By default, a connection timeout of 5 seconds is used when connecting to a remote destination.
You can adjust this by setting the appender's `connectionTimeout` configuration property to the desired value.
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
...
<connectionTimeout>5 seconds</connectionTimeout>
</appender>
```
A value of `0` means "don't use a timeout and wait indefinitely" which often really means "use OS defaults".
This setting accepts a Logback Duration value - see the section dedicated to [Duration Property](#duration-property) for more information about the valid values.
#### Write Buffer Size
By default, a buffer size of 8192 is used to buffer socket output stream writes.
You can adjust this by setting the appender's `writeBufferSize`.
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
...
<writeBufferSize>16384</writeBufferSize>
</appender>
```
Buffering can be disabled by setting the `writeBufferSize` to `0`.
Consider disabling the write buffer if you are concerned about losing data from the buffer for flaky connections.
Disabling the buffer can potentially slow down the writer thread due to increased system calls,
but in some environments, this does not seem to affect overall performance.
See [this discussion](https://github.com/logfellow/logstash-logback-encoder/issues/342).
#### Write Timeouts
If a destination stops reading from its socket input, but does not close the connection, then writes from the TCP appender will eventually backup, causing the ring buffer to backup, causing events to be dropped.
To detect this situation, you can enable a write timeout, so that "stuck" writes will eventually timeout, at which point the connection will be re-established.
When the [write buffer](#write-buffer-size) is enabled, any buffered data will be lost when the connection is reestablished.
By default there is no write timeout. To enable a write timeout, do the following:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
...
<writeTimeout>1 minute</writeTimeout>
</appender>
```
Note that since the blocking java socket output stream used to send events does not have a concept of a write timeout, write timeouts are detected using a task scheduled periodically with the same frequency as the write timeout.
For example, if the write timeout is set to 30 seconds, then a task will execute every 30 seconds to see if 30 seconds has elapsed since the start of the current write operation.
Therefore, it is recommended to use longer write timeouts (e.g. > 30s, or minutes), rather than short write timeouts, so that this task does not execute too frequently.
Also, this approach means that it could take up to two times the write timeout before a write timeout is detected.
The write timeout must be >0. A timeout of zero is interpreted as an infinite timeout which effecively means "no write timeout".
This setting accepts a Logback Duration value - see the section dedicated to [Duration Property](#duration-property) for more information about the valid values.
#### SSL
To use SSL, add an `<ssl>` sub-element within the `<appender>` element for the `LogstashTcpSocketAppender`
or `LogstashAccessTcpSocketAppender`.
See the [logback manual](http://logback.qos.ch/manual/usingSSL.html) for how to configure SSL.
SSL for the `Logstash*TcpSocketAppender`s are configured the same way as logback's `SSLSocketAppender`.
For example, to enable SSL using the JVM's default keystore/truststore, do the following:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
...
<!-- Enable SSL using the JVM's default keystore/truststore -->
<ssl/>
</appender>
```
To use a different truststore, do the following:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashAccessTcpSocketAppender">
...
<!-- Enable SSL and use a different truststore -->
<ssl>
<trustStore>
<location>classpath:server.truststore</location>
<password>${server.truststore.password}</password>
</trustStore>
</ssl>
</appender>
```
All the customizations that [logback](http://logback.qos.ch/manual/usingSSL.html) offers
(such as configuring cipher specs, protocols, algorithms, providers, etc.)
are supported by the `Logback*TcpSocketAppender`s.
See the logstash documentation for the [`tcp`](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-tcp.html) input for how to configure it to use SSL.
### Async Appenders
The `*AsyncDisruptorAppender` appenders are similar to logback's `AsyncAppender`,
except that a [LMAX Disruptor RingBuffer](https://lmax-exchange.github.io/disruptor/)
is used as the queuing mechanism, as opposed to a `BlockingQueue`.
These async appenders can delegate to any other underlying logback appender.
For example:
```xml
<appender name="async" class="net.logstash.logback.appender.LoggingEventAsyncDisruptorAppender">
<appender class="ch.qos.logback.core.rolling.RollingFileAppender">
...
</appender>
</appender>
```
#### RingBuffer Full
The async appenders will by default never block the logging thread.
If the RingBuffer is full (e.g. due to slow network, etc), then events will be dropped.
Alternatively, you can configure the appender to wait until space becomes available instead of dropping the events immediately. This may come in handy when you want to rely on the buffering and the async nature of the appender but don't want to loose any event in case of large logging bursts that exceed the size of the RingBuffer.
The behaviour of the appender when the RingBuffer is controlled by the `appendTimeout` configuration property:
| `appendTimeout` | Behaviour when RingBuffer is full |
|-----------------|------------------------------------------------------------------------|
| `< 0` | disable timeout and wait until space is available |
| `0` | no timeout, give up immediately and drop event (this is the *default*) |
| `> 0` | retry during the specified amount of time |
Logging threads waiting for space in the RingBuffer wake up periodically at a frequency starting at `1ns` and increasing exponentially up to `appendRetryFrequency` (default `5ms`).
Only one thread is allowed to retry at a time. If a thread is already retrying, additional threads are waiting on a lock until the first is finished. This strategy should help to limit CPU consumption while providing good enough latency and throughput when the ring buffer is at (or close) to its maximal capacity.
When the appender drops an event, it emits a warning status message every `droppedWarnFrequency` consecutive dropped events. Another status message is emitted when the drop period is over and a first event is succesfully enqueued reporting the total number of events that were dropped.
#### Graceful Shutdown
In order to guarantees that logged messages have had a chance to be processed by asynchronous appenders (including the TCP appender) and ensure background threads have been stopped, you'll need to [cleanly shut down logback](http://logback.qos.ch/manual/configuration.html#stopContext) when your application exits.
When gracefully stopped, async appenders wait until all events in the buffer are processed and the buffer is empty.
The maximum time to wait is configured by the `shutdownGracePeriod` parameter and is set to `1 minute` by default.
Events still in the buffer after this period is elapsed are dropped and the appender is stopped.
#### Wait Strategy
By default, the [`BlockingWaitStrategy`](https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/BlockingWaitStrategy.html) is used by the worker thread spawned by this appender.
The `BlockingWaitStrategy` minimizes CPU utilization, but results in slower latency and throughput.
If you need faster latency and throughput (at the expense of higher CPU utilization), consider
a different [wait strategy](https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/WaitStrategy.html) offered by the disruptor.
> !! Whichever wait strategy you choose, be sure to test and monitor CPU utilization, latency, and throughput to ensure it meets your needs.
> For example, in some configurations, `SleepingWaitStrategy` can consume 90% CPU utilization at rest.
The wait strategy can be configured on the async appender using the `waitStrategyType` parameter, like this:
```xml
<appender name="async" class="net.logstash.logback.appender.LoggingEventAsyncDisruptorAppender">
<waitStrategyType>sleeping</waitStrategyType>
<appender class="ch.qos.logback.core.rolling.RollingFileAppender">
...
</appender>
</appender>
```
The supported wait strategies are as follows:
<table>
<tbody>
<tr>
<th>Wait Strategy</th>
<th>Parameters</th>
<th>Implementation</th>
</tr>
<tr>
<td><tt>blocking</tt></td>
<td>none</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/BlockingWaitStrategy.html"><tt>BlockingWaitStrategy</tt></a></td>
</tr>
<tr>
<td><tt>busySpin</tt></td>
<td>none</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/BusySpinWaitStrategy.html"><tt>BusySpinWaitStrategy</tt></a></td>
</tr>
<tr>
<td><tt>liteBlocking</tt></td>
<td>none</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/LiteBlockingWaitStrategy.html"><tt>LiteBlockingWaitStrategy</tt></a></td>
</tr>
<tr>
<td><tt>yielding</tt></td>
<td>none</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/YieldingWaitStrategy.html"><tt>YieldingWaitStrategy</tt></a></td>
</tr>
<tr>
<td><pre>sleeping{
<em>retries</em>,
<em>sleepTimeNs</em>
}
</pre>e.g.<br/><tt>sleeping</tt><br/>or<br/><tt>sleeping{500,1000}</tt></td>
<td>
<ol>
<li><tt>retries</tt> - Number of times (integer) to spin before sleeping. (default = 200)</li>
<li><tt>sleepTimeNs</tt> - Time in nanoseconds to sleep each iteration after spinning (default = 100)</li>
</ol>
</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/SleepingWaitStrategy.html"><tt>SleepingWaitStrategy</tt></a></td>
</tr>
<tr>
<td><pre>phasedBackoff{
<em>spinTime</em>,
<em>yieldTime</em>,
<em>timeUnit</em>,
<em>fallbackStrategy</em>
}
</pre>
e.g.<br/><tt>phasedBackoff{10,60,seconds,blocking}</tt></td>
<td>
<ol>
<li><tt>spinTime</tt> - Time to spin before yielding</li>
<li><tt>yieldTime</tt> - Time to yield before falling back to the <tt>fallbackStrategy</tt></li>
<li><tt>timeUnit</tt> - Units of time for spin and yield timeouts. String name of a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html"><tt>TimeUnit</tt></a> value (e.g. <tt>seconds</tt>)</li>
<li><tt>fallbackStrategy</tt> - String name of the wait strategy to fallback to after the timeouts have elapsed</li>
</ol>
</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/PhasedBackoffWaitStrategy.html"><tt>PhasedBackoffWaitStrategy</tt></a></td>
</tr>
<tr>
<td><pre>timeoutBlocking{
<em>timeout</em>,
<em>timeUnit</em>
}
</pre>e.g.<br/><tt>timeoutBlocking{1,minutes}</tt></td>
<td>
<ol>
<li><tt>timeout</tt> - Time to block before throwing an exception</li>
<li><tt>timeUnit</tt> - Units of time for timeout. String name of a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html"><tt>TimeUnit</tt></a> value (e.g. <tt>seconds</tt>)</li>
</ol>
</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/TimeoutBlockingWaitStrategy.html"><tt>TimeoutBlockingWaitStrategy</tt></a></td>
</tr>
<tr>
<td><pre>liteTimeoutBlocking{
<em>timeout</em>,
<em>timeUnit</em>
}
</pre>e.g.<br/><tt>liteTimeoutBlocking{1,minutes}</tt></td>
<td>
<ol>
<li><tt>timeout</tt> - Time to block before throwing an exception</li>
<li><tt>timeUnit</tt> - Units of time for timeout. String name of a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html"><tt>TimeUnit</tt></a> value (e.g. <tt>seconds</tt>)</li>
</ol>
</td>
<td><a href="https://lmax-exchange.github.io/disruptor/docs/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategy.html"><tt>LiteTimeoutBlockingWaitStrategy</tt></a></td>
</tr>
</tbody>
</table>
See [AsyncDisruptorAppender](/src/main/java/net/logstash/logback/appender/AsyncDisruptorAppender.java)
for other configuration parameters (such as `ringBufferSize`, `threadNamePrefix`, `daemon`, and `droppedWarnFrequency`)
### Appender Listeners
Listeners can be registered to an appender to receive notifications for the appender lifecycle and event processing.
See the two listener interfaces for the types of notifications that can be received:
* [`AppenderListener`](/src/main/java/net/logstash/logback/appender/listener/AppenderListener.java) - basic notifications for the [async appenders](#async-appenders) and [udp appender](#udp-appender).
* [`TcpAppenderListener`](/src/main/java/net/logstash/logback/appender/listener/TcpAppenderListener.java) - extension of `AppenderListener` with additional TCP-specific notifications. Only works with the [TCP appenders](#tcp-appenders).
Some example use cases for a listener are:
* Monitoring metrics for events per second, event processing durations, dropped events, connections successes / failures, etc.
* Logging event processing errors to a different appender (that perhaps appends to a different destination).
A [`FailureSummaryLoggingAppenderListener`](src/main/java/net/logstash/logback/appender/listener/FailureSummaryLoggingAppenderListener.java)
is provided that will log a warning on the first success after a series of consecutive append/send/connect failures.
The message includes summary details of the failures that occurred (such as the number of failures, duration of the failures, etc).
To register it:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashAccessTcpSocketAppender">
<listener class="net.logstash.logback.appender.listener.FailureSummaryLoggingAppenderListener">
<loggerName>net.logstash.logback.appender.listener.FailureSummaryLoggingAppenderListener</loggerName>
</listener>
</appender>
```
You may also create your own listener by implementing the `*Listener` interface and register it to an appender using the `listener` xml element like this:
```xml
<appender name="stash" class="net.logstash.logback.appender.LogstashAccessTcpSocketAppender">
...
<listener class="your.package.YourListenerClass">
<yourListenerProperty>propertyValue</yourListenerProperty>
</listener>
</appender>
```
Multiple listeners can be registered by supplying multiple `listener` xml elements.
### Encoders / Layouts
You can use any of the encoders/layouts provided by the logstash-logback-encoder library with other logback appenders.
For example, to output LoggingEvents to a file, use the `LogstashEncoder`
with the `RollingFileAppender` in your `logback.xml` like this:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stash" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>info</level>
</filter>
<file>/some/path/to/your/file.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/some/path/to/your/file.log.%d{yyyy-MM-dd}</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder class="net.logstash.logback.encoder.LogstashEncoder" />
</appender>
<root level="all">
<appender-ref ref="stash" />
</root>
</configuration>
```
To log AccessEvents to a file, configure your `logback-access.xml` like this:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stash" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/some/path/to/your/file.log</file>
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder" />
</appender>
<appender-ref ref="stash" />
</configuration>
```
The `LogstashLayout` and `LogstashAccessLayout` can be configured the same way as
the `LogstashEncoder` and `LogstashAccessEncoder`. All the other examples
in this document use encoders, but the same options apply to the layouts as well.
To receive file input in logstash, configure a [`file`](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-file.html) input in logstash's configuration like this:
```
input {
file {
path => "/some/path/to/your/file.log"
codec => "json"
}
}
```
## LoggingEvent Fields
The following sections describe the fields included in the JSON output by default for LoggingEvents written by the
* `LogstashEncoder`
* `LogstashLayout`, and
* the logstash appenders
If you are using the [composite encoders/layouts](#composite-encoderlayout), then the fields written will
vary by the providers you configure.
### Standard Fields
These fields will appear in every LoggingEvent unless otherwise noted.
The field names listed here are the default field names.
The field names can be customized (see [Customizing Standard Field Names](#customizing-standard-field-names)).
| Field | Description
|---------------|------------
| `@timestamp` | Time of the log event (`yyyy-MM-dd'T'HH:mm:ss.SSSZZ`) - see [Customizing Timestamp](#customizing-timestamp)
| `@version` | Logstash format version (e.g. `1`) - see [Customizing Version](#customizing-version)
| `message` | Formatted log message of the event - see [Customizing Message](#customizing-message)
| `logger_name` | Name of the logger that logged the event
| `thread_name` | Name of the thread that logged the event
| `level` | String name of the level of the event
| `level_value` | Integer value of the level of the event
| `stack_trace` | (Only if a throwable was logged) The stacktrace of the throwable. Stackframes are separated by line endings.
| `tags` | (Only if tags are found) The names of any markers not explicitly handled. (e.g. markers from `MarkerFactory.getMarker` will be included as tags, but the markers from [`Markers`](/src/main/java/net/logstash/logback/marker/Markers.java) will not.) This can be fully disabled by specifying `<includeTags>false</includeTags>`, in the encoder/layout/appender configuration.
### MDC fields
By default, each entry in the Mapped Diagnostic Context (MDC) (`org.slf4j.MDC`)
will appear as a field in the LoggingEvent.
This can be fully disabled by specifying `<includeMdc>false</includeMdc>`,
in the encoder/layout/appender configuration.
You can also configure specific entries in the MDC to be included or excluded as follows:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<includeMdcKeyName>key1ToInclude</includeMdcKeyName>
<includeMdcKeyName>key2ToInclude</includeMdcKeyName>
</encoder>
```
or
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<excludeMdcKeyName>key1ToExclude</excludeMdcKeyName>
<excludeMdcKeyName>key2ToExclude</excludeMdcKeyName>
</encoder>
```
When key names are specified for inclusion, then all other fields will be excluded.
When key names are specified for exclusion, then all other fields will be included.
It is a configuration error to specify both included and excluded key names.
By default, the MDC key is used as the field name in the output.
To use an alternative field name in the output for an MDC entry,
specify`<mdcKeyFieldName>mdcKeyName=fieldName</mdcKeyFieldName>`:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<mdcKeyFieldName>key1=alternateFieldNameForKey1</mdcKeyFieldName>
</encoder>
```
### Context fields
By default, each property of Logback's Context (`ch.qos.logback.core.Context`)
will appear as a field in the LoggingEvent.
This can be disabled by specifying `<includeContext>false</includeContext>`
in the encoder/layout/appender configuration.
Note that logback versions prior to 1.1.10 included a `HOSTNAME` property by default in the context.
As of logback 1.1.10, the `HOSTNAME` property is lazily calculated (see [LOGBACK-1221](https://jira.qos.ch/browse/LOGBACK-1221)), and will no longer be included by default.
### Caller Info Fields
The encoder/layout/appender do not contain caller info by default.
This can be costly to calculate and should be switched off for busy production environments.
To switch it on, add the `includeCallerData` property to the configuration.
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<includeCallerData>true</includeCallerData>
</encoder>
```
If the encoder is included inside an asynchronous appender, such as
`AsyncAppender`, `LoggingEventAsyncDisruptorAppender`, or `LogstashTcpSocketAppender`, then
`includeCallerData` must be set to true on the appender as well.
When switched on, the following fields will be included in the log event:
| Field | Description
|----------------------|------------
| `caller_class_name` | Fully qualified class name of the class that logged the event
| `caller_method_name` | Name of the method that logged the event
| `caller_file_name` | Name of the file that logged the event
| `caller_line_number` | Line number of the file where the event was logged
### Custom Fields
In addition to the fields above, you can add other fields to the LoggingEvent either globally, or on an event-by-event basis.
#### Global Custom Fields
Add custom fields that will appear in every LoggingEvent like this :
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"appname":"myWebservice","roles":["customerorder","auth"],"buildinfo":{"version":"Version 0.1.0-SNAPSHOT","lastcommit":"75473700d5befa953c45f630c6d9105413c16fe1"}}</customFields>
</encoder>
```
or in an AccessEvent like this :
```xml
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<customFields>{"appname":"myWebservice","roles":["customerorder","auth"],"buildinfo":{"version":"Version 0.1.0-SNAPSHOT","lastcommit":"75473700d5befa953c45f630c6d9105413c16fe1"}}</customFields>
</encoder>
```
#### Event-specific Custom Fields
When logging a message, you can add additional fields to the JSON output by using
* _structured arguments_ provided by
[`StructuredArguments`](/src/main/java/net/logstash/logback/argument/StructuredArguments.java), OR
* _markers_ provided by
[`Markers`](/src/main/java/net/logstash/logback/marker/Markers.java)
The difference between the two is that
* `StructuredArguments` are included in a the log event's formatted message
(when the message has a parameter for the argument) _AND_ in the JSON output.
* `StructuredArguments` will be included in the JSON output if using `LogstashEncoder/Layout`
or if using [composite encoders/layouts](#composite-encoderlayout) with the `arguments` provider.
* `Markers` are only written to the JSON output, and _NEVER_ to the log event's formatted message.
* `Markers` will be included in the JSON output if using `LogstashEncoder/Layout`
or if using [composite encoders/layouts](#composite-encoderlayout) with the `logstashMarkers` provider.
You can use `StructuredArguments` even if the message does not contain a parameter
for the argument. However, in this case, the argument will only be written to the JSON output
and not the formatted message (which is effectively the same behavior that the Markers provide).
In general, you should use `StructuredArguments`, unless you have a static analyzer
that flags parameter count / argument count mismatches.
Both `StructuredArguments` and `Markers` require constructing additional objects.
Therefore, it is best practice to surround the log lines with `logger.isXXXEnabled()`,
to avoid the object construction if the log level is disabled.
Examples using `StructuredArguments`:
```java
import static net.logstash.logback.argument.StructuredArguments.*;
/*
* Add "name":"value" to the JSON output,
* but only add the value to the formatted message.
*
* The formatted message will be `log message value`
*/
logger.info("log message {}", value("name", "value"));
/*
* Add "name":"value" to the JSON output,
* and add name=value to the formatted message.
*
* The formatted message will be `log message name=value`
*/
logger.info("log message {}", keyValue("name", "value"));
/*
* Add "name":"value" ONLY to the JSON output.
*
* Since there is no parameter for the argument,
* the formatted message will NOT contain the key/value.
*
* If this looks funny to you or to static analyzers,
* consider using Markers instead.
*/
logger.info("log message", keyValue("name", "value"));
/*
* Add multiple key value pairs to both JSON and formatted message
*/
logger.info("log message {} {}", keyValue("name1", "value1"), keyValue("name2", "value2")));
/*
* Add "name":"value" to the JSON output and
* add name=[value] to the formatted message using a custom format.
*/
logger.info("log message {}", keyValue("name", "value", "{0}=[{1}]"));
/*
* In the JSON output, values will be serialized by Jackson's ObjectMapper.
* In the formatted message, values will follow the same behavior as logback
* (formatting of an array or if not an array `toString()` is called).
*
* Add "foo":{...} to the JSON output and add `foo.toString()` to the formatted message:
*
* The formatted message will be `log message <result of foo.toString()>`
*/
Foo foo = new Foo();
logger.info("log message {}", value("foo", foo));
/*
* Add "name1":"value1","name2":"value2" to the JSON output by using a Map,
* and add `myMap.toString()` to the formatted message.
*
* Note the values can be any object that can be serialized by Jackson's ObjectMapper
* (e.g. other Maps, JsonNodes, numbers, arrays, etc)
*/
Map myMap = new HashMap();
myMap.put("name1", "value1");
myMap.put("name2", "value2");
logger.info("log message {}", entries(myMap));
/*
* Add "array":[1,2,3] to the JSON output,
* and array=[1,2,3] to the formatted message.
*/
logger.info("log message {}", array("array", 1, 2, 3));
/*
* Add fields of any object that can be unwrapped by Jackson's UnwrappableBeanSerializer to the JSON output.
* i.e. The fields of an object can be written directly into the JSON output.
* This is similar to the @JsonUnwrapped annotation.
*
* The formatted message will contain `myobject.toString()`
*/
logger.info("log message {}", fields(myobject));
/*
* In order to normalize a field object name, static helper methods can be created.
* For example:
* public static StructuredArgument foo(Foo foo) {
* return StructuredArguments.value("foo", foo);
* }
*/
logger.info("log message {}", foo(foo));
```
Abbreviated convenience methods are available for all the structured argument types.
For example, instead of `keyValue(key, value)`, you can use `kv(key, value)`.
Examples using `Markers`:
```java
import static net.logstash.logback.marker.Markers.*;
/*
* Add "name":"value" to the JSON output.
*/
logger.info(append("name", "value"), "log message");
/*
* Add "name1":"value1","name2":"value2" to the JSON output by using multiple markers.
*/
logger.info(append("name1", "value1").and(append("name2", "value2")), "log message");
/*
* Add "name1":"value1","name2":"value2" to the JSON output by using a map.
*
* Note the values can be any object that can be serialized by Jackson's ObjectMapper
* (e.g. other Maps, JsonNodes, numbers, arrays, etc)
*/
Map myMap = new HashMap();
myMap.put("name1", "value1");
myMap.put("name2", "value2");
logger.info(appendEntries(myMap), "log message");
/*
* Add "array":[1,2,3] to the JSON output
*/
logger.info(appendArray("array", 1, 2, 3), "log message");
/*
* Add "array":[1,2,3] to the JSON output by using raw json.
* This allows you to use your own json seralization routine to construct the json output
*/
logger.info(appendRaw("array", "[1,2,3]"), "log message");
/*
* Add any object that can be serialized by Jackson's ObjectMapper
* (e.g. Maps, JsonNodes, numbers, arrays, etc)
*/
logger.info(append("object", myobject), "log message");
/*
* Add fields of any object that can be unwrapped by Jackson's UnwrappableBeanSerializer.
* i.e. The fields of an object can be written directly into the json output.
* This is similar to the @JsonUnwrapped annotation.
*/
logger.info(appendFields(myobject), "log message");
```
## AccessEvent Fields
The following sections describe the fields included in the JSON output by default for AccessEvents written by the
* `LogstashAccessEncoder`,
* `LogstashAccessLayout`, and
* the logstash access appenders.
If you are using the [composite encoders/layouts](#composite-encoderlayout), then the fields written will
vary by the providers you configure.
### Standard Fields
These fields will appear in every AccessEvent unless otherwise noted.
The field names listed here are the default field names.
The field names can be customized (see [Customizing Standard Field Names](#customizing-standard-field-names)).
| Field | Description
|---------------|------------
| `@timestamp` | Time of the log event. (`yyyy-MM-dd'T'HH:mm:ss.SSSZZ`) See [customizing timestamp](#customizing-timestamp).
| `@version` | Logstash format version (e.g. `1`) See [customizing version](#customizing-version).
| `message` | Message in the form `${remoteHost} - ${remoteUser} [${timestamp}] "${requestUrl}" ${statusCode} ${contentLength}`
| `method` | HTTP method
| `protocol` | HTTP protocol
| `status_code` | HTTP status code
| `requested_url` | Request URL
| `requested_uri` | Request URI
| `remote_host` | Remote host
| `remote_user` | Remote user
| `content_length` | Content length
| `elapsed_time` | Elapsed time in millis
### Header Fields
Request and response headers are not logged by default, but can be enabled by specifying a field name for them, like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<fieldNames>
<requestHeaders>request_headers</requestHeaders>
<responseHeaders>response_headers</responseHeaders>
</fieldNames>
</encoder>
```
See [Customizing Standard Field Names](#customizing-standard-field-names)) for more details.
To write the header names in lowercase (so that header names that only differ by case are treated the same),
set `lowerCaseFieldNames` to true, like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<fieldNames>
<requestHeaders>request_headers</requestHeaders>
<responseHeaders>response_headers</responseHeaders>
</fieldNames>
<lowerCaseHeaderNames>true</lowerCaseHeaderNames>
</encoder>
```
Headers can be filtered via configuring the `requestHeaderFilter` and/or the `responseHeaderFilter`
with a [`HeaderFilter`](/src/main/java/net/logstash/logback/composite/accessevent/HeaderFilter.java), such as the
[`IncludeExcludeHeaderFilter`](/src/main/java/net/logstash/logback/composite/accessevent/IncludeExcludeHeaderFilter.java).
The `IncludeExcludeHeaderFilter` can be configured like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<fieldNames>
<requestHeaders>request_headers</requestHeaders>
</fieldNames>
<requestHeaderFilter>
<include>Content-Type</include>
</requestHeaderFilter>
</encoder>
```
Custom filters implementing [`HeaderFilter`](/src/main/java/net/logstash/logback/composite/accessevent/HeaderFilter.java)
can be used by specifying the filter class like this:
```xml
<requestHeaderFilter class="your.package.YourFilterClass"/>
```
## Customizing Jackson
Logstash-logback-encoder uses [Jackson](https://github.com/FasterXML/jackson) to encode log and access events.
Logstash-logback-encoder provides sensible defaults for Jackson, but gives you full control over the Jackson configuration.
For example, you can:
* specify the [data format](#data-format)
* customize the [`JsonFactory` and `JsonGenerator`](#customizing-json-factory-and-generator)
* register [jackson modules](#registering-jackson-modules)
* configure [character escapes](#customizing-character-escapes)
### Data Format
JSON is used by default, but other data formats supported by Jackson can be used.
* [text data formats](https://github.com/FasterXML/jackson-dataformats-text)
* [binary data formats](https://github.com/FasterXML/jackson-dataformats-binary)
> :warning: When using non-JSON data formats, you must include the appropriate jackson dataformat library on the runtime classpath,
> typically via a maven/gradle dependency (e.g. for Smile, include `jackson-dataformat-smile`).
[Decorators](#customizing-json-factory-and-generator) are provided for the following data formats:
* `cbor` - [`CborJsonFactoryDecorator`](src/main/java/net/logstash/logback/decorate/cbor/CborJsonFactoryDecorator.java)
* `smile` - [`SmileJsonFactoryDecorator`](src/main/java/net/logstash/logback/decorate/smile/SmileJsonFactoryDecorator.java)
* `yaml` - [`YamlJsonFactoryDecorator`](src/main/java/net/logstash/logback/decorate/yaml/YamlJsonFactoryDecorator.java)
To use one these formats, specify the `<jsonFactoryDecorator>` like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonFactoryDecorator class="net.logstash.logback.decorate.smile.SmileJsonFactoryDecorator"/>
</encoder>
```
Other data formats can be used by implementing a custom
[`net.logstash.logback.decorate.JsonFactoryDecorator`](src/main/java/net/logstash/logback/decorate/JsonFactoryDecorator.java).
The following [decorators](#customizing-json-factory-and-generator)
can be used to configure data-format-specific generator features:
* [`SmileFeatureJsonGeneratorDecorator`](src/main/java/net/logstash/logback/decorate/smile/SmileFeatureJsonGeneratorDecorator.java)
* [`CborFeatureJsonGeneratorDecorator`](src/main/java/net/logstash/logback/decorate/cbor/CborFeatureJsonGeneratorDecorator.java)
* [`YamlFeatureJsonGeneratorDecorator`](src/main/java/net/logstash/logback/decorate/yaml/YamlFeatureJsonGeneratorDecorator.java)
For example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonFactoryDecorator class="net.logstash.logback.decorate.smile.SmileJsonFactoryDecorator"/>
<jsonGeneratorDecorator class="net.logstash.logback.decorate.smile.SmileFeatureJsonGeneratorDecorator">
<disable>WRITE_HEADER</disable>
</jsonGeneratorDecorator>
</encoder>
```
### Customizing JSON Factory and Generator
The `JsonFactory` and `JsonGenerator` used to write output can be customized by instances of:
* [`JsonFactoryDecorator`](/src/main/java/net/logstash/logback/decorate/JsonFactoryDecorator.java)
* [`JsonGeneratorDecorator`](/src/main/java/net/logstash/logback/decorate/JsonGeneratorDecorator.java)
For example, you could enable pretty printing by using the
[PrettyPrintingJsonGeneratorDecorator](/src/main/java/net/logstash/logback/decorate/PrettyPrintingJsonGeneratorDecorator.java)
Or customize object mapping like this:
```java
public class ISO8601DateDecorator implements JsonFactoryDecorator {
@Override
public JsonFactory decorate(JsonFactory factory) {
ObjectMapper codec = (ObjectMapper) factory.getCodec();
codec.setDateFormat(new ISO8601DateFormat());
return factory;
}
}
```
and then specify the decorators in the logback.xml file like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonGeneratorDecorator class="net.logstash.logback.decorate.PrettyPrintingJsonGeneratorDecorator"/>
<jsonFactoryDecorator class="your.package.ISO8601DateDecorator"/>
</encoder>
```
`JsonFactory` and `JsonGenerator` features can be enabled/disabled by using the
`FeatureJsonFactoryDecorator` and `FeatureJsonGeneratorDecorator`, respectively.
For example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonFactoryDecorator class="net.logstash.logback.decorate.FeatureJsonFactoryDecorator">
<disable>USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING</disable>
</jsonFactoryDecorator>
<jsonGeneratorDecorator class="net.logstash.logback.decorate.FeatureJsonGeneratorDecorator">
<enable>WRITE_NUMBERS_AS_STRINGS</enable>
</jsonGeneratorDecorator>
</encoder>
```
See the [net.logstash.logback.decorate](/src/main/java/net/logstash/logback/decorate) package
and sub-packages for other decorators.
### Registering Jackson Modules
By default, Jackson modules are dynamically registered via
[`ObjectMapper.findAndRegisterModules()`](https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/ObjectMapper.html#findAndRegisterModules--).
Therefore, you just need to add jackson modules (e.g. jackson-datatype-jdk8) to the classpath,
and they will be dynamically registered.
To disable automatic discovery, set `<findAndRegisterJacksonModules>false</findAndRegisterJacksonModules>` on the encoder/layout.
If you have a module that Jackson is not able to dynamically discover,
you can register it manually via a [`JsonFactoryDecorator`](#customizing-json-factory-and-generator).
### Customizing Character Escapes
By default, when a string is written as a JSON string value, any character not allowed in a JSON string will be escaped.
For example, the newline character (ASCII 10) will be escaped as `\n`.
To customize these escape sequences, use the `net.logstash.logback.decorate.CharacterEscapesJsonFactoryDecorator`.
For example, if you want to use something other than `\n` as the escape sequence for the newline character, you can do the following:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonFactoryDecorator class="net.logstash.logback.decorate.CharacterEscapesJsonFactoryDecorator">
<escape>
<targetCharacterCode>10</targetCharacterCode>
<escapeSequence>\u2028</escapeSequence>
</escape>
</jsonFactoryDecorator>
</encoder>
```
You can also disable all the default escape sequences by specifying `<includeStandardAsciiEscapesForJSON>false</includeStandardAsciiEscapesForJSON>` on the `CharacterEscapesJsonFactoryDecorator`.
If you do this, then you will need to register custom escapes for each character that is illegal in JSON string values. Otherwise, invalid JSON could be written.
## Masking
The [`MaskingJsonGeneratorDecorator`](src/main/java/net/logstash/logback/mask/MaskingJsonGeneratorDecorator.java)
can be used to mask sensitive values (e.g. personally identifiable information (PII) or financial data).
Data to be masked can be identified by [path](#identifying-field-values-to-mask-by-path)
and/or by [value](#identifying-field-values-to-mask-by-value).
### Identifying field values to mask by path
Paths of fields to mask can be specified in several ways, as shown in the following example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonGeneratorDecorator class="net.logstash.logback.mask.MaskingJsonGeneratorDecorator">
<!-- The default mask string can optionally be specified by <defaultMask>.
When the default mask string is not specified, **** is used.
-->
<defaultMask>****</defaultMask>
<!-- Field paths to mask added via <path> will use the default mask string -->
<path>singleFieldName</path>
<path>/absolute/path/to/mask</path>
<path>partial/path/to/mask</path>
<path>partial/path/with/*/wildcard</path>
<path>tilde~0slash~1escapedPath</path>
<!-- Multiple field paths can be specified as a comma separated string in the <paths> element. -->
<paths>path1,path2,path3</paths>
<!-- Field paths to mask added via <pathMask> can use a non-default mask string -->
<pathMask>
<path>some/path</path>
<path>some/other/path</path>
<mask>[masked]</mask>
</pathMask>
<pathMask>
<paths>anotherFieldName,anotherFieldName2</paths>
<mask>**anotherCustomMask**</mask>
</pathMask>
<!-- Field paths to mask can be supplied dynamically with an implementation
of MaskingJsonGeneratorDecorator.PathMaskSupplier
-->
<pathMaskSupplier class="your.custom.PathMaskSupplierA"/>
<!-- Custom implementations of net.logstash.logback.mask.FieldMasker
can be used for more advanced masking behavior
-->
<fieldMasker class="your.custom.FieldMaskerA"/>
<fieldMasker class="your.custom.FieldMaskerB"/>
</jsonGeneratorDecorator>
</encoder>
```
See [`PathBasedFieldMasker`](src/main/java/net/logstash/logback/mask/PathBasedFieldMasker.java)
for the path string format and more examples. But in general:
* Paths follow a format similar to (but not _exactly_ same as) a [JSON Pointer](http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-03).
* Absolute paths start with `/` and are absolute to the root of the JSON output event (e.g. `/@timestamp` would mask the default timestamp field)
* Partial paths do not start with `/` and match anywhere that path sequence is seen in the output.
* A path with a single token (i.e. no `/` characters) will match all occurrences of a field with the given name
* A wildcard token (`*`) will match anything at that location within the path
* Use `~1` to escape `/` within a token
* Use `~0` to escape `~` within a token
### Identifying field values to mask by value
Specific values to be masked can be specified in several ways, as seen in the following example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonGeneratorDecorator class="net.logstash.logback.mask.MaskingJsonGeneratorDecorator">
<!-- The default mask string can optionally be specified by <defaultMask>.
When the default mask string is not specified, **** is used.
-->
<defaultMask>****</defaultMask>
<!-- Values to mask added via <value> will use the default mask string -->
<value>^foo$</value>
<value>bar</value>
<!-- Multiple values can be specified as a comma separated string in the <values> element. -->
<values>^baz$,^blah$</values>
<!-- Values to mask added via <valueMask> can use a non-default mask string
The mask string here can reference regex capturing groups if needed
-->
<valueMask>
<value>^(foo)-.*$</value>
<value>^(bar)-.*$</value>
<mask>$1****</mask>
</valueMask>
<!-- Values to mask can be supplied dynamically with an implementation of
MaskingJsonGeneratorDecorator.ValueMaskSupplier
-->
<valueMaskSupplier class="your.custom.ValueMaskSupplierA"/>
<!-- Custom implementations of net.logstash.logback.mask.ValueMasker
can be used for more advanced masking behavior
-->
<valueMasker class="your.custom.ValueMaskerA"/>
<valueMasker class="your.custom.ValueMaskerB"/>
</jsonGeneratorDecorator>
</encoder>
```
Identifying data to mask by value is much more expensive than identifying data to mask by [path](#identifying-field-values-to-mask-by-path).
Therefore, prefer identifying data to mask by path.
The value to mask is passed through every value masker, with the output of one masker passed as input to the next masker.
This allows each masker to mask specific substrings within the value.
The order in which the maskers are executed is not defined, and should not be relied upon.
When using regexes to identify strings to mask, all matches within each string field value will be replaced.
If you want to match the full string field value, then use the beginning of line (`^`) and end of line (`$`) markers.
## Customizing Standard Field Names
The standard field names above for LoggingEvents and AccessEvents can be customized by using the `fieldNames`configuration element in the encoder or appender configuration.
For example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<fieldNames>
<timestamp>time</timestamp>
<message>msg</message>
<stackTrace>stacktrace</stackTrace>
...
</fieldNames>
</encoder>
```
Prevent a field from being output by setting the field name to `[ignore]`.
For LoggingEvents, see [`LogstashFieldNames`](/src/main/java/net/logstash/logback/fieldnames/LogstashFieldNames.java)
for all the field names that can be customized. Each java field name in that class is the name of the xml element that you would use to specify the field name (e.g. `logger`, `levelValue`). Additionally, a separate set of [shortened field names](/src/main/java/net/logstash/logback/fieldnames/ShortenedFieldNames.java) can be configured like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<fieldNames class="net.logstash.logback.fieldnames.ShortenedFieldNames"/>
</encoder>
```
For LoggingEvents, log the caller info, MDC properties, and context properties
in sub-objects within the JSON event by specifying field
names for `caller`, `mdc`, and `context`, respectively.
For AccessEvents, see [`LogstashAccessFieldNames`](/src/main/java/net/logstash/logback/fieldnames/LogstashAccessFieldNames.java)
for all the field names that can be customized. Each java field name in that class is the name of the xml element that you would use to specify the field name (e.g. `fieldsMethod`, `fieldsProtocol`).
## Customizing Version
The version field value by default is the string value `1`.
The value can be changed like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<version>2</version>
</encoder>
```
The value can be written as a number (instead of a string) like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<writeVersionAsInteger>true</writeVersionAsInteger>
</encoder>
```
## Customizing Timestamp
By default, timestamps are written as string values in the format specified by
[`DateTimeFormatter.ISO_OFFSET_DATE_TIME`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE_TIME)
(e.g. `2019-11-03T10:15:30.123+01:00`), in the default TimeZone of the host Java platform.
You can change the pattern like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<timestampPattern>yyyy-MM-dd'T'HH:mm:ss.SSS</timestampPattern>
</encoder>
```
The value of the `timestampPattern` can be any of the following:
* `[UNIX_TIMESTAMP_AS_NUMBER]` - timestamp written as a JSON number value of the milliseconds since unix epoch
* `[UNIX_TIMESTAMP_AS_STRING]` - timestamp written as a JSON string value of the milliseconds since unix epoch
* `[` _`constant`_ `]` - (e.g. `[ISO_OFFSET_DATE_TIME]`) timestamp written using the given `DateTimeFormatter` constant
* any other value - (e.g. `yyyy-MM-dd'T'HH:mm:ss.SSS`) timestamp written using a `DateTimeFormatter` created from the given pattern
The provider uses a standard Java DateTimeFormatter under the hood. However, special optimisations are applied when using one of the following standard ISO formats that make it nearly 7x faster:
* `[ISO_OFFSET_DATE_TIME]`
* `[ISO_ZONED_DATE_TIME`]
* `[ISO_LOCAL_DATE_TIME`]
* `[ISO_DATE_TIME`]
* `[ISO_INSTANT`]
The formatter uses the default TimeZone of the host Java platform by default. You can change it like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<timeZone>UTC</timeZone>
</encoder>
```
The value of the `timeZone` element can be any string accepted by java's `TimeZone.getTimeZone(String id)` method.
For example `America/Los_Angeles`, `GMT+10` or `UTC`.
Use the special value `[DEFAULT]` to use the default TimeZone of the system.
## Customizing LoggingEvent Message
By default, LoggingEvent messages are written as JSON strings. Any characters not allowed in a JSON string, such as newlines, are escaped.
See the [Customizing Character Escapes](#customizing-character-escapes) section for details.
You can also write messages as JSON arrays instead of strings, by specifying a `messageSplitRegex` to split the message text.
This configuration element can take the following values:
* any valid regex pattern
* `SYSTEM` (uses the system-default line separator)
* `UNIX` (uses `\n`)
* `WINDOWS` (uses `\r\n`)
If you split the log message by the origin system's line separator, the written message does not contain any embedded line separators.
The target system can unambiguously parse the message without any knowledge of the origin system's line separators.
For example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<messageSplitRegex>SYSTEM</messageSplitRegex>
</encoder>
```
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<messageSplitRegex>\r?\n</messageSplitRegex>
</encoder>
```
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<messageSplitRegex>#+</messageSplitRegex>
</encoder>
```
## Customizing AccessEvent Message
By default, AccessEvent messages are written in the following format:
```
%clientHost - %user [%date] "%requestURL" %statusCode %bytesSent
```
To customize the message pattern, specify the `messagePattern` like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<messagePattern>%clientHost [%date] "%requestURL" %statusCode %bytesSent</messagePattern>
</encoder>
```
The pattern can contain any of the [AccessEvent conversion words](http://logback.qos.ch/manual/layouts.html#AccessPatternLayout).
## Customizing Logger Name Length
For LoggingEvents, you can shorten the logger name field length similar to the normal pattern style of `%logger{36}`.
Examples of how it is shortened can be found [here](http://logback.qos.ch/manual/layouts.html#conversionWord)
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<shortenedLoggerNameLength>36</shortenedLoggerNameLength>
</encoder>
```
## Customizing Stack Traces
When [logging exceptions](https://www.baeldung.com/slf4j-log-exceptions),
stack traces are formatted using logback's `ExtendedThrowableProxyConverter` by default.
However, you can configure the encoder to use any `ThrowableHandlingConverter`
to format stacktraces.
Note that the `ThrowableHandlingConverter` only applies to the
[exception passed as an extra argument](https://www.baeldung.com/slf4j-log-exceptions)
to the log method, the way you normally log an exception in slf4j.
Do NOT use [structured arguments or markers](#event-specific-custom-fields) for exceptions.
A powerful [`ShortenedThrowableConverter`](/src/main/java/net/logstash/logback/stacktrace/ShortenedThrowableConverter.java)
is included in the logstash-logback-encoder library to format stacktraces by:
* Limiting the number of stackTraceElements per throwable (applies to each individual throwable. e.g. caused-bys and suppressed)
* Limiting the total length in characters of the trace
* Abbreviating class names
* Filtering out consecutive unwanted stackTraceElements based on regular expressions.
* Using evaluators to determine if the stacktrace should be logged.
* Outputting in either 'normal' order (root-cause-last), or root-cause-first.
* Computing and inlining hexadecimal hashes for each exception stack using the `inlineHash` or `stackHash` provider ([more info](stack-hash.md)).
* Using custom line separator for stack traces. The line separator can be specified as:
* `SYSTEM` (uses the system default)
* `UNIX` (uses `\n`)
* `WINDOWS` (uses `\r\n`), or
* any other string.
For example:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
<maxDepthPerThrowable>30</maxDepthPerThrowable>
<maxLength>2048</maxLength>
<shortenedClassNameLength>20</shortenedClassNameLength>
<exclude>sun\.reflect\..*\.invoke.*</exclude>
<exclude>net\.sf\.cglib\.proxy\.MethodProxy\.invoke</exclude>
<evaluator class="myorg.MyCustomEvaluator"/>
<rootCauseFirst>true</rootCauseFirst>
<inlineHash>true</inlineHash>
<lineSeparator>\\n</lineSeparator>
</throwableConverter>
</encoder>
```
[`ShortenedThrowableConverter`](/src/main/java/net/logstash/logback/stacktrace/ShortenedThrowableConverter.java)
can even be used within a `PatternLayout` to format stacktraces in any non-JSON logs you may have.
## Prefix/Suffix/Separator
You can specify a prefix (written before the JSON object),
suffix (written after the JSON object),
and/or line separator (written after suffix),
which may be required for the log pipeline you are using, such as:
* If you are using the Common Event Expression (CEE) format for syslog, you need to add the `@cee:` prefix.
* If you are using other syslog destinations, you might need to add the standard syslog headers.
* If you are using Loggly, you might need to add your customer token.
For example, to add standard syslog headers for syslog over UDP, configure the following:
```xml
<configuration>
<conversionRule conversionWord="syslogStart" converterClass="ch.qos.logback.classic.pattern.SyslogStartConverter"/>
<appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
<host>MyAwesomeSyslogServer</host>
<!-- port is optional (default value shown) -->
<port>514</port>
<layout>
<prefix class="ch.qos.logback.classic.PatternLayout">
<pattern>%syslogStart{USER}</pattern>
</prefix>
</layout>
</appender>
...
</configuration>
```
When using the `LogstashEncoder`, `LogstashAccessEncoder` or a composite encoder, the prefix is an `Encoder`, not a `Layout`, so you will need to wrap the prefix `PatternLayout` in a `LayoutWrappingEncoder` like this:
```xml
<configuration>
...
<appender ...>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
...
<prefix class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>@cee:</pattern>
</layout>
</prefix>
</encoder>
</appender>
</configuration>
```
Note that logback's xml configuration reader will [trim whitespace from xml element values](https://github.com/qos-ch/logback/blob/c2dcbfcfb4048d11d7e81cd9220efbaaccf931fa/logback-core/src/main/java/ch/qos/logback/core/joran/event/BodyEvent.java#L27-L37). Therefore, if you want to end the prefix or suffix pattern with whitespace, first add the whitespace, and then add something like `%mdc{keyThatDoesNotExist}` after it. For example `<pattern>your pattern %mdc{keyThatDoesNotExist}</pattern>`. This will cause logback to output the whitespace as desired, and then a blank string for the MDC key that does not exist.
> :warning: If you encounter the following warning: `A "net.logstash.logback.encoder.LogstashEncoder" object is not assignable to a "ch.qos.logback.core.Appender" variable.`, you are encountering a backwards incompatibilility introduced in logback 1.2.1. Please vote for [LOGBACK-1326](https://jira.qos.ch/browse/LOGBACK-1326) and add a thumbs up to [PR#383](https://github.com/qos-ch/logback/pull/383) to try to get this addressed in logback. In the meantime, the only solution is to downgrade logback-classic and logback-core to 1.2.0
The line separator, which is written after the suffix, can be specified as:
* `SYSTEM` (uses the system default)
* `UNIX` (uses `\n`)
* `WINDOWS` (uses `\r\n`), or
* any other string.
For example:
```xml
<configuration>
...
<appender ...>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
...
<lineSeparator>UNIX</lineSeparator>
</encoder>
</appender>
</configuration>
```
## Composite Encoder/Layout
If you want greater flexibility in the JSON format and data included in LoggingEvents and AccessEvents, use the [`LoggingEventCompositeJsonEncoder`](/src/main/java/net/logstash/logback/encoder/LoggingEventCompositeJsonEncoder.java) and [`AccessEventCompositeJsonEncoder`](/src/main/java/net/logstash/logback/encoder/AccessEventCompositeJsonEncoder.java) (or the corresponding layouts).
These encoders/layouts are composed of one or more JSON _providers_ that contribute to the JSON output. No providers are configured by default in the composite encoders/layouts. You must add the ones you want.
For example:
```xml
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<mdc/>
<pattern>
<pattern>
{
"timestamp": "%date{ISO8601}",
"myCustomField": "fieldValue",
"relative": "#asLong{%relative}"
}
</pattern>
</pattern>
<stackTrace>
<throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
<maxDepthPerThrowable>30</maxDepthPerThrowable>
<maxLength>2048</maxLength>
<shortenedClassNameLength>20</shortenedClassNameLength>
<exclude>^sun\.reflect\..*\.invoke</exclude>
<exclude>^net\.sf\.cglib\.proxy\.MethodProxy\.invoke</exclude>
<evaluator class="myorg.MyCustomEvaluator"/>
<rootCauseFirst>true</rootCauseFirst>
</throwableConverter>
</stackTrace>
</providers>
</encoder>
```
The logstash-logback-encoder library contains many providers out-of-the-box,
and you can even plug-in your own by extending `JsonProvider`.
Each provider has its own configuration options to further customize it.
These encoders/layouts make use of an internal buffer to hold the JSON output during the rendering process.
The size of this buffer is set to `1024` bytes by default. A different size can be configured by setting the `minBufferSize` property to the desired value.
The buffer automatically grows above the `minBufferSize` when needed to accommodate with larger events. However, only the first `minBufferSize` bytes will be reused by subsequent invocations. It is therefore strongly advised to set the minimum size at least equal to the average size of the encoded events to reduce unnecessary memory allocations and reduce pressure on the garbage collector.
### Providers common to LoggingEvents and AccessEvents
The table below lists the providers available to both _LoggingEvents_ and _AccessEvents_.
The provider name is the xml element name to use when configuring.
<table>
<tbody>
<tr>
<th>Provider</th>
<th>Description/Properties</th>
</tr>
<tr>
<td valign="top"><tt>context</tt></td>
<td><p>Outputs entries from logback's context.</p>
<ul>
<li><tt>fieldName</tt> - Sub-object field name (no sub-object)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>nestedField</tt></td>
<td>
<p>Nests a JSON object under the configured fieldName.</p>
<p>The nested object is populated by other providers added to this provider.</p>
<p>See <a href="#provider_nested">Nested JSON provider</a>.</p>
<ul>
<li><tt>fieldName</tt> - Output field name</li>
<li><tt>providers</tt> - The providers that should populate the nested object.</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>pattern</tt></td>
<td>
<p>Outputs fields from a configured JSON Object string,
while substituting patterns supported by logback's <tt>PatternLayout</tt>.
</p>
<p>
See <a href="#provider_pattern">Pattern JSON Provider</a>
</p>
<ul>
<li><tt>pattern</tt> - JSON object string (no default)</li>
<li><tt>omitEmptyFields</tt> - whether to omit fields with empty values (<tt>false</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>sequence</tt></td>
<td>
<p>
Outputs an incrementing sequence number for every log event.
Useful for tracking pottential message loss during transport (eg. UDP).
</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>sequence</tt>)</li></ul>
</td>
</tr>
<tr>
<td valign="top"><tt>threadName</tt></td>
<td><p>Name of the thread from which the event was logged.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>thread_name</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>timestamp</tt></td>
<td><p>Event timestamp.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>@timestamp</tt>)</li>
<li><tt>pattern</tt> - Output format (<tt>[ISO_OFFSET_DATE_TIME]</tt>) See <a href="#customizing-timestamp">above</a> for possible values.</li>
<li><tt>timeZone</tt> - Timezone (system timezone)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>uuid</tt></td>
<td>
<p>
Outputs random UUID as field value. Handy when you want to provide unique identifier
for log lines.
</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>uuid</tt>)</li>
<li><tt>strategy</tt> - UUID generation strategy (<tt>random</tt>). Supported options: <ul><li><tt>random</tt> - for Type 4 UUID</li>
<li><tt>time</tt> - for Type 1 time based UUID</li>
</ul></li>
<li><tt>ethernet</tt> - Only for 'time' strategy. When defined - MAC address to use for location part of UUID. Set it to <tt>interface</tt> value to use real underlying network interface or to specific values like <tt>00:C0:F0:3D:5B:7C</tt></li>
</ul>
<p>Note: The <a href="https://mvnrepository.com/artifact/com.fasterxml.uuid/java-uuid-generator/"><tt>com.fasterxml.uuid:java-uuid-generator</tt></a> optional dependency must be added to applications that use the `uuid` provider.</p>
</td>
</tr>
<tr>
<td valign="top"><tt>version</tt></td>
<td><p>Logstash JSON format version.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>@version</tt>)</li>
<li><tt>version</tt> - Output value (<tt>1</tt>)</li>
<li><tt>writeAsInteger</tt> - Write the version as a integer value (<tt>false</tt> = write as a string value)</li>
</ul>
</td>
</tr>
</tbody>
</table>
### Providers for LoggingEvents
The [common providers mentioned above](#providers-common-to-loggingevents-and-accessevents), and the providers listed in the table below, are available for _LoggingEvents_.
The provider name is the xml element name to use when configuring. Each provider's configuration properties are shown, with default configuration values in parenthesis.
<table>
<tbody>
<tr>
<th>Provider</th>
<th>Description/Properties</th>
</tr>
<tr>
<td valign="top"><tt>arguments</tt></td>
<td>
<p>Outputs fields from the event arguments array.</p>
<p>See <a href="#event-specific-custom-fields">Event-specific Custom Fields</a>.</p>
<ul>
<li><tt>fieldName</tt> - Sub-object field name (no sub-object)</li>
<li><tt>includeNonStructuredArguments</tt> - Include arguments that are not an instance
of <a href="/src/main/java/net/logstash/logback/argument/StructuredArgument.java"><tt>StructuredArgument</tt></a>.
Object field name will be <tt>nonStructuredArgumentsFieldPrefix</tt> prepend to the argument index.
(default=false)
</li>
<li><tt>nonStructuredArgumentsFieldPrefix</tt> - Object field name prefix (default=arg)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>callerData</tt></td>
<td><p>Outputs data about from where the logger was called (class/method/file/line).</p>
<ul>
<li><tt>fieldName</tt> - Sub-object field name (no sub-object)</li>
<li><tt>classFieldName</tt> - Field name for class name (<tt>caller_class_name</tt>)</li>
<li><tt>methodFieldName</tt> - Field name for method name (<tt>caller_method_name</tt>)</li>
<li><tt>fileFieldName</tt> - Field name for file name (<tt>caller_file_name</tt>)</li>
<li><tt>lineFieldName</tt> - Field name for line number (<tt>caller_line_number</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>contextName</tt></td>
<td><p>Outputs the name of logback's context.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>context</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>loggerName</tt></td>
<td><p>Name of the logger that logged the message.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>logger_name</tt>)</li>
<li><tt>shortenedLoggerNameLength</tt> - Length to which the name will be attempted to be abbreviated (no abbreviation)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>logLevel</tt></td>
<td><p>Logger level text (INFO, WARN, etc).</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>level</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>logLevelValue</tt></td>
<td><p>Logger level numerical value.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>level_value</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>logstashMarkers</tt></td>
<td><p>Used to output Logstash Markers as specified in <em>Event-specific Custom Fields</em>.</p>
</td>
</tr>
<tr>
<td valign="top"><tt>mdc</tt></td>
<td>
<p>Outputs entries from the Mapped Diagnostic Context (MDC).
Will include all entries by default.
When key names are specified for inclusion, then all other fields will be excluded.
When key names are specified for exclusion, then all other fields will be included.
It is a configuration error to specify both included and excluded key names.
</p>
<ul>
<li><tt>fieldName</tt> - Sub-object field name (no sub-object)</li>
<li><tt>includeMdcKeyName</tt> - Name of keys to include (all)</li>
<li><tt>excludeMdcKeyName</tt> - Name of keys to exclude (none)</li>
<li><tt>mdcKeyFieldName</tt> - Strings in the form <tt>mdcKeyName=fieldName</tt>
that specify an alternate field name to output for specific MDC key (none)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>message</tt></td>
<td><p>Formatted log event message.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>message</tt>)</li>
<li><tt>messageSplitRegex</tt> - If null or empty, write the message text as is (the default behavior).
Otherwise, split the message text using the specified regex and write it as an array.
See the <a href="#customizing-message">Customizing Message</a> section for details.</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>rawMessage</tt></td>
<td><p>Raw log event message, as opposed to formatted log where parameters are resolved.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>raw_message</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>rootStackTraceElement</tt></td>
<td><p>(Only if a throwable was logged) Outputs a JSON Object containing the class and method name from which the outer-most exception was thrown.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>root_stack_trace_element</tt>)</li>
<li><tt>classFieldName</tt> - Field name containing the class name from which the outermost exception was thrown (<tt>class_name</tt>)</li>
<li><tt>methodFieldName</tt> - Field name containing the method name from which the outermost exception was thrown (<tt>method_name</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>stackHash</tt></td>
<td><p>(Only if a throwable was logged) Computes and outputs a hexadecimal hash of the throwable stack.</p>
<p>This helps identifying several occurrences of the same error (<a href="stack-hash.md">more info</a>).</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>stack_hash</tt>)</li>
<li><tt>exclude</tt> - Regular expression pattern matching <i>stack trace elements</i> to exclude when computing the error hash</li>
<li><tt>exclusions</tt> - Comma separated list of regular expression patterns matching <i>stack trace elements</i> to exclude when computing the error hash</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>stackTrace</tt></td>
<td><p>Stacktrace of any throwable logged with the event. Stackframes are separated by newline chars.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>stack_trace</tt>)</li>
<li><tt>throwableConverter</tt> - The <tt>ThrowableHandlingConverter</tt> to use to format the stacktrace (<tt>stack_trace</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>tags</tt></td>
<td><p>Outputs logback markers as a comma separated list.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>tags</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>throwableClassName</tt></td>
<td><p>(Only if a throwable was logged) Outputs a field that contains the class name of the thrown Throwable.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>throwable_class</tt>)</li>
<li><tt>useSimpleClassName</tt> - When true, the throwable's simple class name will be used. When false, the fully qualified class name will be used. (<tt>true</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>throwableMessage</tt></td>
<td><p>(Only if a throwable was logged) Outputs a field that contains the message of the thrown Throwable.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>throwable_message</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>throwableRootCauseClassName</tt></td>
<td><p>(Only if a throwable was logged and a root cause could be determined) Outputs a field that contains the class name of the root cause of the thrown Throwable.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>throwable_root_cause_class</tt>)</li>
<li><tt>useSimpleClassName</tt> - When true, the throwable's simple class name will be used. When false, the fully qualified class name will be used. (<tt>true</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>throwableRootCauseMessage</tt></td>
<td><p>(Only if a throwable was logged and a root cause could be determined) Outputs a field that contains the message of the root cause of the thrown Throwable.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>throwable_root_cause_message</tt>)</li>
</ul>
</td>
</tr>
</tbody>
</table>
### Providers for AccessEvents
The [common providers mentioned above](#providers-common-to-loggingevents-and-accessevents), and the providers listed in the table below, are available for _AccessEvents_.
The provider name is the xml element name to use when configuring. Each provider's configuration properties are shown, with default configuration values in parenthesis.
<table>
<tbody>
<tr>
<th>Provider</th>
<th>Description/Properties</th>
</tr>
<tr>
<td valign="top"><tt>contentLength</tt></td>
<td><p>Content length.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>content_length</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>elapsedTime</tt></td>
<td><p>Elapsed time in milliseconds.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>elapsed_time</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>message</tt></td>
<td><p>Message in the form `${remoteHost} - ${remoteUser} [${timestamp}] "${requestUrl}" ${statusCode} ${contentLength}`.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>message</tt>)</li>
<li><tt>pattern</tt> - Output format of the timestamp (<tt>[ISO_OFFSET_DATE_TIME]</tt>). See <a href="#customizing-timestamp">above</a> for possible values.</li>
<li><tt>timeZone</tt> - Timezone (system timezone)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>method</tt></td>
<td><p>HTTP method.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>method</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>protocol</tt></td>
<td><p>HTTP protocol.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>protocol</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>remoteHost</tt></td>
<td><p>Remote Host.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>remote_host</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>remoteUser</tt></td>
<td><p>Remote User.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>remote_user</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>requestedUri</tt></td>
<td><p>Requested URI.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>requested_uri</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>requestedUrl</tt></td>
<td><p>Requested URL.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>requested_url</tt>)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>requestHeaders</tt></td>
<td><p>Include the request headers.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (no default, must be provided)</li>
<li><tt>lowerCaseHeaderNames</tt> - Write header names in lower case (<tt>false</tt>)</li>
<li><tt>filter</tt> - A filter to determine which headers to include/exclude.
See <a href="/src/main/java/net/logstash/logback/composite/accessevent/HeaderFilter.java"><tt>HeaderFilter</tt></a>
and <a href="/src/main/java/net/logstash/logback/composite/accessevent/IncludeExcludeHeaderFilter.java"><tt>IncludeExcludeHeaderFilter</tt></a></li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>responseHeaders</tt></td>
<td><p>Include the response headers.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (no default, must be provided)</li>
<li><tt>lowerCaseHeaderNames</tt> - Write header names in lower case (<tt>false</tt>)</li>
<li><tt>filter</tt> - A filter to determine which headers to include/exclude.
See <a href="/src/main/java/net/logstash/logback/composite/accessevent/HeaderFilter.java"><tt>HeaderFilter</tt></a>
and <a href="/src/main/java/net/logstash/logback/composite/accessevent/IncludeExcludeHeaderFilter.java"><tt>IncludeExcludeHeaderFilter</tt></a></li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><tt>statusCode</tt></td>
<td><p>HTTP status code.</p>
<ul>
<li><tt>fieldName</tt> - Output field name (<tt>status_code</tt>)</li>
</ul>
</td>
</tr>
</tbody>
</table>
### Nested JSON Provider
Use the `nestedField` provider to create a sub-object in the JSON event output.
For example...
```xml
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<timestamp/>
<nestedField>
<fieldName>fields</fieldName>
<providers>
<logLevel/>
</providers>
</nestedField>
</providers>
</encoder>
```
...will produce something like...
```json
{
"@timestamp": "...",
"fields": {
"level": "DEBUG"
}
}
```
### Pattern JSON Provider
When used with a composite JSON encoder/layout, the `pattern` JSON provider can be used to
define a template for a portion of the logged JSON output.
The encoder/layout will populate values within the template.
Every value in the template is treated as a pattern for logback's standard `PatternLayout` so it can be a combination
of literal strings (for some constants) and various conversion specifiers (like `%d` for date).
The pattern string (configured within the pattern provider) must be a JSON Object.
The contents of the JSON object are included within the logged JSON output.
This example...
```xml
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<!-- provides the timestamp -->
<timestamp/>
<!-- provides the version -->
<version/>
<!-- provides the fields in the configured pattern -->
<pattern>
<!-- the pattern that defines what to include -->
<pattern>
{ "level": "%level" }
</pattern>
</pattern>
</providers>
</encoder>
```
... will produce something like...
```
{
"@timestamp": "...",
"@version": "1",
"level": "DEBUG"
}
```
The real power comes from the fact that there are lots of standard conversion specifiers so you
can customise what is logged and how. For example, you could log a single specific value from MDC with `%mdc{mykey}`.
Or, for access logs, you could log a single request header with `%i{User-Agent}`.
You can use nested objects and arrays in your pattern.
If you use a null, number, or a boolean constant in a pattern, it will keep its type in the
resulting JSON. However, only the text values are searched for conversion patterns.
And, as these patterns are sent through `PatternLayout`, the result is always a string
even for something which you may feel should be a number - like for `%b` (bytes sent, in access logs).
You can either deal with the type conversion on the logstash side or you may use special operations provided by this encoder.
The operations are:
* `#asLong{...}` - evaluates the pattern in curly braces and then converts resulting string to a Long (or a `null` if conversion fails).
* `#asDouble{...}` - evaluates the pattern in curly braces and then converts resulting string to a Double (or a `null` if conversion fails).
* `#asBoolean{...}`- evaluates the pattern in curly braces and then converts resulting string to a Boolean. Conversion is case insensitive. `true`, `yes`, `y` and `1` (case insensitive) are converted to a boolean `true`, a `null` or empty string is converted to `null`, anything else returns `false`.
* `asNullIfEmpty{...}` - evaluates the pattern in curly braces and the converts resulting string into `null` if it is empty.
* `#asJson{...}` - evaluates the pattern in curly braces and then converts resulting string to json (or a `null` if conversion fails).
* `#tryJson{...}` - evaluates the pattern in curly braces and then converts resulting string to json (or just the string if conversion fails).
So this example...
```xml
<pattern>
{
"line_str": "%line",
"line_long": "#asLong{%line}",
"has_message": "#asBoolean{%mdc{hasMessage}}",
"json_message": "#asJson{%message}"
}
</pattern>
```
... and this logging code...
```java
MDC.put("hasMessage", "true");
LOGGER.info("{\"type\":\"example\",\"msg\":\"example of json message with type\"}");
```
...will produce something like...
```json
{
"line_str": "97",
"line_long": 97,
"has_message": true,
"json_message": {"type":"example","msg":"example of json message with type"}
}
```
Note that the value that is sent for `line_long` is a number even though in your pattern it is a quoted text.
And the `json_message` field value is a json object, not a string.
You can escape an operation by prefixing it with `\` if you don't want it to be interpreted.
#### Omitting fields with empty values
The pattern provider can be configured to omit fields with the following _empty_ values:
* `null`
* empty string (`""`)
* empty array (`[]`)
* empty object (`{}`)
* objects containing only fields with empty values
* arrays containing only empty values
To omit fields with empty values, configure `omitEmptyFields` to `true` (default is `false`), like this:
```xml
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<pattern>
<omitEmptyFields>true</omitEmptyFields>
<pattern>
{
"logger": "%logger",
"level": "%level",
"thread": "%thread",
"message": "%message",
"traceId": "%mdc{traceId}"
}
</pattern>
</pattern>
</providers>
</encoder>
```
If the MDC did not contain a `traceId` entry, then a JSON log event from the above pattern would not contain the `traceId` field...
```json
{
"logger": "com.example...",
"level": "DEBUG",
"thread": "exec-1",
"message": "Hello World!"
}
```
#### LoggingEvent patterns
For LoggingEvents, conversion specifiers from logback-classic's
[`PatternLayout`](http://logback.qos.ch/manual/layouts.html#conversionWord) are supported.
For example:
```xml
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<timestamp/>
<pattern>
<pattern>
{
"custom_constant": "123",
"tags": ["one", "two"],
"logger": "%logger",
"level": "%level",
"thread": "%thread",
"message": "%message",
...
}
</pattern>
</pattern>
</providers>
</encoder>
```
Note that the [`%property{key}`](https://logback.qos.ch/manual/layouts.html#property) conversion specifier behaves slightly differently when used in the context of the Pattern Json provider. If the property cannot be found in the logger context or the System properties, it returns **an empty string** instead of `null` as it would normally do. For example, assuming the "foo" property is not defined, `%property{foo}` would return `""` (an empty string) instead of `"null"` (a string whose content is made of 4 letters).
The _property_ conversion specifier also allows you to specify a default value to use when the property is not defined. The default value is optional and can be specified using the `:-` operator as in Bash shell. For example, assuming the "foo" property is not defined, `%property{foo:-bar}` will return `bar`.
#### AccessEvent patterns
For AccessEvents, conversion specifiers from logback-access's
[`PatternLayout`](http://logback.qos.ch/xref/ch/qos/logback/access/PatternLayout.html) are supported.
For example:
```xml
<encoder class="net.logstash.logback.encoder.AccessEventCompositeJsonEncoder">
<providers>
<pattern>
<pattern>
{
"custom_constant": "123",
"tags": ["one", "two"],
"remote_ip": "%a",
"status_code": "%s",
"elapsed_time": "%D",
"user_agent": "%i{User-Agent}",
"accept": "%i{Accept}",
"referer": "%i{Referer}",
"session": "%requestCookie{JSESSIONID}",
...
}
</pattern>
</pattern>
</providers>
</encoder>
```
There is also a special operation that can be used with this AccessEvents:
* `#nullNA{...}` - if the pattern in curly braces evaluates to a dash (`-`), it will be replaced with a `null` value.
You may want to use it because many of the `PatternLayout` conversion words from logback-access will evaluate to `-`
for non-existent value (for example for a cookie, header or a request attribute).
So the following pattern...
```xml
<pattern>
{
"default_cookie": "%requestCookie{MISSING}",
"filtered_cookie": "#nullNA{%requestCookie{MISSING}}"
}
</pattern>
```
...will produce...
```json
{
"default_cookie": "-",
"filtered_cookie": null
}
```
### Custom JSON Provider
You can create your own JSON provider by implementing the [`JsonProvider`](src/main/java/net/logstash/logback/composite/JsonProvider.java) interface (or extending one of the existing classes that implements the `JsonProvider` interface).
Then, add the provider to a `LoggingEventCompositeJsonEncoder` like this:
```xml
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
...
<provider class="your.provider.YourJsonProvider">
<!-- Any properties exposed by your provider can be set here -->
</provider>
...
</providers>
</encoder>
```
or a `LogstashEncoder` like this:
```xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
...
<provider class="your.provider.YourJsonProvider">
<!-- Any properties exposed by your provider can be set here -->
</provider>
...
</encoder>
```
You can do something similar for `AccessEventCompositeJsonEncoder` and `LogstashAccessEncoder` as well, if your `JsonProvider` handles `IAccessEvent`s.
## Status Listeners
During execution, the encoders/appenders/layouts provided in logstash-logback-encoder
will add logback status messages to the logback [`StatusManager`](https://logback.qos.ch/apidocs/ch/qos/logback/core/status/StatusManager.html).
These status messages are typically reported via a logback [`StatusListener`](https://logback.qos.ch/apidocs/ch/qos/logback/core/status/StatusListener.html).
Since the [async appenders](#async-appenders) (especially the [tcp appenders](#tcp-appenders))
report warnings and errors via the status manager, a default status listener that
outputs WARN and ERROR level status messages to standard out
will be registered on startup if a status listener has not already been registered.
To disable the automatic registering of the default status listener by an appender, do one of the following:
* register a different logback [status listener](https://logback.qos.ch/manual/configuration.html#dumpingStatusData), or
* set `<addDefaultStatusListener>false</addDefaultStatusListener` in each async appender.
## Joran/XML Configuration
Configuring Logback using XML is handled by Logback's Joran configuration system. This section is a short description of the high level data types supported by Joran. For more information, please refer to the [official documentation](http://logback.qos.ch/manual).
### Duration property
Duration represents a laps of time.
It can be specified as an integer value representing a number of milliseconds, or a string such as "20 seconds", "3.5 minutes" or "5 hours" that will be automatically converted by logback's configuration system into Duration instances.
The recognized units of time are the `millisecond`, `second`, `minute`, `hour` and `day`. The unit name may be followed by an "s". Thus, "2000 millisecond" and "2000 milliseconds" are equivalent. In the absence of a time unit specification, milliseconds are assumed.
The following examples are therefore equivalent:
```xml
<duration>2000</duration>
<duration>2000 millisecond</duration>
<duration>2000 milliseconds</duration>
```
## Profiling
<a href="https://www.yourkit.com/java/profiler/"><img src="http://www.yourkit.com/images/yklogo.png" alt="YourKit Logo" height="22"/></a>
Memory usage and performance of logstash-logback-encoder have been improved
by addressing issues discovered with the help of the
[YourKit Java Profiler](https://www.yourkit.com/java/profiler/).
YourKit, LLC has graciously donated a free license of the
[YourKit Java Profiler](https://www.yourkit.com/java/profiler/)
to this open source project.
|