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
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.valves;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.AccessLog;
import org.apache.catalina.Globals;
import org.apache.catalina.Session;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.TLSUtil;
import org.apache.coyote.ActionCode;
import org.apache.coyote.RequestInfo;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.buf.HexUtils;
import org.apache.tomcat.util.collections.SynchronizedStack;
import org.apache.tomcat.util.net.IPv6Utils;
/**
* Abstract implementation of the <b>Valve</b> interface that generates a web server access log with the detailed line
* contents matching a configurable pattern. The syntax of the available patterns is similar to that supported by the
* <a href="https://httpd.apache.org/">Apache HTTP Server</a> <code>mod_log_config</code> module.
* <p>
* Patterns for the logged message may include constant text or any of the following replacement strings, for which the
* corresponding information from the specified Response is substituted:
* <ul>
* <li><b><code>%a</code></b> - Remote IP address
* <li><b><code>%A</code></b> - Local IP address
* <li><b><code>%b</code></b> - Bytes sent, excluding HTTP headers, or '-' if no bytes were sent
* <li><b><code>%B</code></b> - Bytes sent, excluding HTTP headers
* <li><b><code>%h</code></b> - Remote host name (or IP address if <code>enableLookups</code> for the connector is
* false)
* <li><b><code>%H</code></b> - Request protocol
* <li><b><code>%l</code></b> - Remote logical username from identd (always returns '-')
* <li><b><code>%m</code></b> - Request method
* <li><b><code>%p</code></b> - Local port
* <li><b><code>%q</code></b> - Query string (prepended with a '?' if it exists, otherwise an empty string
* <li><b><code>%r</code></b> - First line of the request
* <li><b><code>%s</code></b> - HTTP status code of the response
* <li><b><code>%S</code></b> - User session ID
* <li><b><code>%t</code></b> - Date and time, in Common Log Format format
* <li><b><code>%u</code></b> - Remote user that was authenticated
* <li><b><code>%U</code></b> - Requested URL path
* <li><b><code>%v</code></b> - Local server name
* <li><b><code>%D</code></b> - Time taken to process the request, in microseconds
* <li><b><code>%T</code></b> - Time taken to process the request, in seconds
* <li><b><code>%F</code></b> - Time taken to commit the response, in milliseconds
* <li><b><code>%I</code></b> - current Request thread name (can compare later with stacktraces)
* <li><b><code>%X</code></b> - Connection status when response is completed:
* <ul>
* <li><code>X</code> = Connection aborted before the response completed.</li>
* <li><code>+</code> = Connection may be kept alive after the response is sent.</li>
* <li><code>-</code> = Connection will be closed after the response is sent.</li>
* </ul>
* </ul>
* <p>
* In addition, the caller can specify one of the following aliases for commonly utilized patterns:
* <ul>
* <li><b>common</b> - <code>%h %l %u %t "%r" %s %b</code>
* <li><b>combined</b> - <code>%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"</code>
* </ul>
* <p>
* There is also support to write information from the cookie, incoming header, the Session or something else in the
* ServletRequest.<br>
* It is modeled after the <a href="https://httpd.apache.org/">Apache HTTP Server</a> log configuration syntax:
* <ul>
* <li><code>%{xxx}i</code> for incoming headers
* <li><code>%{xxx}o</code> for outgoing response headers
* <li><code>%{xxx}c</code> for a specific cookie
* <li><code>%{xxx}r</code> xxx is an attribute in the ServletRequest
* <li><code>%{xxx}s</code> xxx is an attribute in the HttpSession
* <li><code>%{xxx}t</code> xxx is an enhanced SimpleDateFormat pattern (see Configuration Reference document for
* details on supported time patterns)
* <li><code>%{xxx}L</code> xxx is the identifier to log (see Configuration Reference document for details on supported
* identifiers)
* <li><code>%{xxx}T</code> xxx is the unit for the time taken to process the request (see Configuration Reference
* document for details on supported units)
* </ul>
* <p>
* Conditional logging is also supported. This can be done with the <code>conditionUnless</code> and
* <code>conditionIf</code> properties. If the value returned from ServletRequest.getAttribute(conditionUnless) yields a
* non-null value, the logging will be skipped. If the value returned from ServletRequest.getAttribute(conditionIf)
* yields the null value, the logging will be skipped. The <code>condition</code> attribute is synonym for
* <code>conditionUnless</code> and is provided for backwards compatibility.
* <p>
* For extended attributes coming from a getAttribute() call, it is you responsibility to ensure there are no newline or
* control characters.
*/
public abstract class AbstractAccessLogValve extends ValveBase implements AccessLog {
private static final Log log = LogFactory.getLog(AbstractAccessLogValve.class);
/**
* The list of our time format types.
*/
private enum FormatType {
CLF,
SEC,
MSEC,
MSEC_FRAC,
SDF
}
/**
* The list of our port types.
*/
private enum PortType {
LOCAL,
REMOTE
}
/**
* The list of our ip address types.
*/
private enum RemoteAddressType {
REMOTE,
PEER
}
private enum IdentifierType {
CONNECTION,
UNKNOWN
}
public AbstractAccessLogValve() {
super(true);
}
// ----------------------------------------------------- Instance Variables
/**
* enabled this component
*/
protected boolean enabled = true;
/**
* Use IPv6 canonical representation format as defined by RFC 5952.
*/
private boolean ipv6Canonical = false;
/**
* The pattern used to format our access log lines.
*/
protected String pattern = null;
/**
* The size of our global date format cache
*/
private static final int globalCacheSize = 300;
/**
* The size of our thread local date format cache
*/
private static final int localCacheSize = 60;
/**
* <p>
* Cache structure for formatted timestamps based on seconds.
* </p>
* <p>
* The cache consists of entries for a consecutive range of seconds. The length of the range is configurable. It is
* implemented based on a cyclic buffer. New entries shift the range.
* </p>
* <p>
* There is one cache for the CLF format (the access log standard format) and a HashMap of caches for additional
* formats used by SimpleDateFormat.
* </p>
* <p>
* Although the cache supports specifying a locale when retrieving a formatted timestamp, each format will always
* use the locale given when the format was first used. New locales can only be used for new formats. The CLF format
* will always be formatted using the locale <code>en_US</code>.
* </p>
* <p>
* The cache is not threadsafe. It can be used without synchronization via thread local instances, or with
* synchronization as a global cache.
* </p>
* <p>
* The cache can be created with a parent cache to build a cache hierarchy. Access to the parent cache is
* threadsafe.
* </p>
* <p>
* This class uses a small thread local first level cache and a bigger synchronized global second level cache.
* </p>
*/
protected static class DateFormatCache {
protected class Cache {
/* CLF log format */
private static final String cLFFormat = "dd/MMM/yyyy:HH:mm:ss Z";
/* Second used to retrieve CLF format in most recent invocation */
private long previousSeconds = Long.MIN_VALUE;
/* Value of CLF format retrieved in most recent invocation */
private String previousFormat = "";
/* First second contained in cache */
private long first = Long.MIN_VALUE;
/* Last second contained in cache */
private long last = Long.MIN_VALUE;
/* Index of "first" in the cyclic cache */
private int offset = 0;
/* Helper object to be able to call SimpleDateFormat.format(). */
private final Date currentDate = new Date();
protected final String[] cache;
private final SimpleDateFormat formatter;
private boolean isCLF = false;
private final Cache parent;
private Cache(Cache parent) {
this(null, parent);
}
private Cache(String format, Cache parent) {
this(format, null, parent);
}
private Cache(String format, Locale loc, Cache parent) {
cache = new String[cacheSize];
for (int i = 0; i < cacheSize; i++) {
cache[i] = null;
}
if (loc == null) {
loc = cacheDefaultLocale;
}
if (format == null) {
isCLF = true;
format = cLFFormat;
formatter = new SimpleDateFormat(format, Locale.US);
} else {
formatter = new SimpleDateFormat(format, loc);
}
formatter.setTimeZone(TimeZone.getDefault());
this.parent = parent;
}
private String getFormatInternal(long time) {
long seconds = time / 1000;
/*
* First step: if we have seen this timestamp during the previous call, and we need CLF, return the
* previous value.
*/
if (seconds == previousSeconds) {
return previousFormat;
}
/* Second step: Try to locate in cache */
previousSeconds = seconds;
int index = (offset + (int) (seconds - first)) % cacheSize;
if (index < 0) {
index += cacheSize;
}
if (seconds >= first && seconds <= last) {
if (cache[index] != null) {
/* Found, so remember for next call and return. */
previousFormat = cache[index];
return previousFormat;
}
/* Third step: not found in cache, adjust cache and add item */
} else if (seconds >= last + cacheSize || seconds <= first - cacheSize) {
first = seconds;
last = first + cacheSize - 1;
index = 0;
offset = 0;
for (int i = 1; i < cacheSize; i++) {
cache[i] = null;
}
} else if (seconds > last) {
for (int i = 1; i < seconds - last; i++) {
cache[(index + cacheSize - i) % cacheSize] = null;
}
first = seconds - (cacheSize - 1);
last = seconds;
offset = (index + 1) % cacheSize;
} else if (seconds < first) {
for (int i = 1; i < first - seconds; i++) {
cache[(index + i) % cacheSize] = null;
}
first = seconds;
last = seconds + (cacheSize - 1);
offset = index;
}
/*
* Last step: format new timestamp either using parent cache or locally.
*/
if (parent != null) {
synchronized (parent) {
previousFormat = parent.getFormatInternal(time);
}
} else {
currentDate.setTime(time);
previousFormat = formatter.format(currentDate);
if (isCLF) {
previousFormat = "[" + previousFormat + "]";
}
}
cache[index] = previousFormat;
return previousFormat;
}
}
/* Number of cached entries */
private int cacheSize = 0;
private final Locale cacheDefaultLocale;
private final DateFormatCache parent;
protected final Cache cLFCache;
private final Map<String,Cache> formatCache = new HashMap<>();
protected DateFormatCache(int size, Locale loc, DateFormatCache parentFC) {
cacheSize = size;
cacheDefaultLocale = loc;
parent = parentFC;
Cache parentCache = null;
if (parent != null) {
synchronized (parent) {
parentCache = parent.getCache(null, null);
}
}
cLFCache = new Cache(parentCache);
}
private Cache getCache(String format, Locale loc) {
Cache cache;
if (format == null) {
cache = cLFCache;
} else {
cache = formatCache.get(format);
if (cache == null) {
Cache parentCache = null;
if (parent != null) {
synchronized (parent) {
parentCache = parent.getCache(format, loc);
}
}
cache = new Cache(format, loc, parentCache);
formatCache.put(format, cache);
}
}
return cache;
}
public String getFormat(long time) {
return cLFCache.getFormatInternal(time);
}
public String getFormat(String format, Locale loc, long time) {
return getCache(format, loc).getFormatInternal(time);
}
}
/**
* Global date format cache.
*/
private static final DateFormatCache globalDateCache =
new DateFormatCache(globalCacheSize, Locale.getDefault(), null);
/**
* Thread local date format cache.
*/
private static final ThreadLocal<DateFormatCache> localDateCache =
ThreadLocal.withInitial(() -> new DateFormatCache(localCacheSize, Locale.getDefault(), globalDateCache));
/**
* The system time when we last updated the Date that this valve uses for log lines.
*/
private static final ThreadLocal<Date> localDate = ThreadLocal.withInitial(Date::new);
/**
* Are we doing conditional logging ? default null. It is the value of <code>conditionUnless</code> property.
*/
protected String condition = null;
/**
* Are we doing conditional logging ? default null. It is the value of <code>conditionIf</code> property.
*/
protected String conditionIf = null;
/**
* Name of locale used to format timestamps in log entries and in log file name suffix.
*/
protected String localeName = Locale.getDefault().toString();
/**
* Locale used to format timestamps in log entries and in log file name suffix.
*/
protected Locale locale = Locale.getDefault();
/**
* Array of AccessLogElement, they will be used to make log message.
*/
protected AccessLogElement[] logElements = null;
/**
* Array of elements where the value needs to be cached at the start of the request.
*/
protected CachedElement[] cachedElements = null;
/**
* Should this valve use request attributes for IP address, hostname, protocol and port used for the request.
* Default is <code>false</code>.
*
* @see #setRequestAttributesEnabled(boolean)
*/
protected boolean requestAttributesEnabled = false;
/**
* Buffer pool used for log message generation. Pool used to reduce garbage generation.
*/
private final SynchronizedStack<CharArrayWriter> charArrayWriters = new SynchronizedStack<>();
/**
* Log message buffers are usually recycled and re-used. To prevent excessive memory usage, if a buffer grows beyond
* this size it will be discarded. The default is 256 characters. This should be set to larger than the typical
* access log message size.
*/
private int maxLogMessageBufferSize = 256;
/**
* Does the configured log pattern include a known TLS attribute?
*/
private boolean tlsAttributeRequired = false;
// ------------------------------------------------------------- Properties
public int getMaxLogMessageBufferSize() {
return maxLogMessageBufferSize;
}
public void setMaxLogMessageBufferSize(int maxLogMessageBufferSize) {
this.maxLogMessageBufferSize = maxLogMessageBufferSize;
}
public boolean getIpv6Canonical() {
return ipv6Canonical;
}
public void setIpv6Canonical(boolean ipv6Canonical) {
this.ipv6Canonical = ipv6Canonical;
}
/**
* {@inheritDoc} Default is <code>false</code>.
*/
@Override
public void setRequestAttributesEnabled(boolean requestAttributesEnabled) {
this.requestAttributesEnabled = requestAttributesEnabled;
}
@Override
public boolean getRequestAttributesEnabled() {
return requestAttributesEnabled;
}
/**
* @return the enabled flag.
*/
public boolean getEnabled() {
return enabled;
}
/**
* @param enabled The enabled to set.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return the format pattern.
*/
public String getPattern() {
return this.pattern;
}
/**
* Set the format pattern, first translating any recognized alias.
*
* @param pattern The new pattern
*/
public void setPattern(String pattern) {
if (pattern == null) {
this.pattern = "";
} else if (pattern.equals(Constants.AccessLog.COMMON_ALIAS)) {
this.pattern = Constants.AccessLog.COMMON_PATTERN;
} else if (pattern.equals(Constants.AccessLog.COMBINED_ALIAS)) {
this.pattern = Constants.AccessLog.COMBINED_PATTERN;
} else {
this.pattern = pattern;
}
logElements = createLogElements();
if (logElements != null) {
cachedElements = createCachedElements(logElements);
}
}
/**
* Return whether the attribute name to look for when performing conditional logging. If null, every request is
* logged.
*
* @return the attribute name
*/
public String getCondition() {
return condition;
}
/**
* Set the ServletRequest.attribute to look for to perform conditional logging. Set to null to log everything.
*
* @param condition Set to null to log everything
*/
public void setCondition(String condition) {
this.condition = condition;
}
/**
* Return whether the attribute name to look for when performing conditional logging. If null, every request is
* logged.
*
* @return the attribute name
*/
public String getConditionUnless() {
return getCondition();
}
/**
* Set the ServletRequest.attribute to look for to perform conditional logging. Set to null to log everything.
*
* @param condition Set to null to log everything
*/
public void setConditionUnless(String condition) {
setCondition(condition);
}
/**
* Return whether the attribute name to look for when performing conditional logging. If null, every request is
* logged.
*
* @return the attribute name
*/
public String getConditionIf() {
return conditionIf;
}
/**
* Set the ServletRequest.attribute to look for to perform conditional logging. Set to null to log everything.
*
* @param condition Set to null to log everything
*/
public void setConditionIf(String condition) {
this.conditionIf = condition;
}
/**
* Return the locale used to format timestamps in log entries and in log file name suffix.
*
* @return the locale
*/
public String getLocale() {
return localeName;
}
/**
* Set the locale used to format timestamps in log entries and in log file name suffix. Changing the locale is only
* supported as long as the AccessLogValve has not logged anything. Changing the locale later can lead to
* inconsistent formatting.
*
* @param localeName The locale to use.
*/
public void setLocale(String localeName) {
this.localeName = localeName;
locale = findLocale(localeName, locale);
}
// --------------------------------------------------------- Public Methods
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
if (tlsAttributeRequired) {
// The log pattern uses TLS attributes. Ensure these are populated
// before the request is processed because with NIO2 it is possible
// for the connection to be closed (and the TLS info lost) before
// the access log requests the TLS info. Requesting it now causes it
// to be cached in the request.
request.getAttribute(Globals.CERTIFICATES_ATTR);
}
if (cachedElements != null) {
for (CachedElement element : cachedElements) {
element.cache(request);
}
}
getNext().invoke(request, response);
}
@Override
public void log(Request request, Response response, long time) {
if (!getState().isAvailable() || !getEnabled() || logElements == null ||
condition != null && null != request.getRequest().getAttribute(condition) ||
conditionIf != null && null == request.getRequest().getAttribute(conditionIf)) {
return;
}
CharArrayWriter result = charArrayWriters.pop();
if (result == null) {
result = new CharArrayWriter(128);
}
for (AccessLogElement logElement : logElements) {
logElement.addElement(result, request, response, time);
}
log(result);
if (result.size() <= maxLogMessageBufferSize) {
result.reset();
charArrayWriters.push(result);
}
}
// -------------------------------------------------------- Protected Methods
/**
* Log the specified message.
*
* @param message Message to be logged. This object will be recycled by the calling method.
*/
protected abstract void log(CharArrayWriter message);
// -------------------------------------------------------- Private Methods
/**
* This method returns a Date object that is accurate to within one second. If a thread calls this method to get a
* Date, and it's been less than 1 second since a new Date was created, this method simply gives out the same Date
* again so that the system doesn't spend time creating Date objects unnecessarily.
*
* @param systime The time
*
* @return the date object
*/
private static Date getDate(long systime) {
Date date = localDate.get();
date.setTime(systime);
return date;
}
/**
* Find a locale by name.
*
* @param name The locale name
* @param fallback Fallback locale if the name is not found
*
* @return the locale object
*/
protected static Locale findLocale(String name, Locale fallback) {
if (name == null || name.isEmpty()) {
return Locale.getDefault();
} else {
for (Locale l : Locale.getAvailableLocales()) {
if (name.equals(l.toString())) {
return l;
}
}
}
log.error(sm.getString("accessLogValve.invalidLocale", name));
return fallback;
}
/**
* AccessLogElement writes the partial message into the buffer.
* <p>
* At least one method must be implemented else a loop will occur.
* <p>
* When the deprecated method is removed in Tomcat 12, the default implementation for
* {@link #addElement(CharArrayWriter, Request, Response, long)} will also be removed.
*/
protected interface AccessLogElement {
/**
* Called to create an access log entry.
*
* @param buf The buffer to which the log element should be added
* @param date The time stamp for the start of the request
* @param request The request that triggered this access log entry
* @param response The response to the request that triggered this access log entry
* @param time The time taken in nanoseconds to process the request
*
* @deprecated Unused. Will be removed in Tomcat 12. Use
* {@link #addElement(CharArrayWriter, Request, Response, long)}
*/
@Deprecated
default void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
addElement(buf, request, response, time);
}
/**
* Called to create an access log entry.
*
* @param buf The buffer to which the log element should be added
* @param request The request that triggered this access log entry
* @param response The response to the request that triggered this access log entry
* @param time The time taken in nanoseconds to process the request
*/
default void addElement(CharArrayWriter buf, Request request, Response response, long time) {
Date date = getDate(request.getCoyoteRequest().getStartTime());
addElement(buf, date, request, response, time);
}
}
/**
* Marks an AccessLogElement as needing to have the value cached at the start of the request rather than just
* recorded at the end as the source data for the element may not be available at the end of the request. This
* typically occurs for remote network information, such as ports, IP addresses etc. when the connection is closed
* unexpectedly. These elements take advantage of these values being cached elsewhere on first request and do not
* cache the value in the element since the elements are state-less.
*/
protected interface CachedElement {
void cache(Request request);
}
/**
* write thread name - %I
*/
protected static class ThreadNameElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
RequestInfo info = request.getCoyoteRequest().getRequestProcessor();
if (info != null) {
buf.append(info.getWorkerThreadName());
} else {
buf.append('-');
}
}
}
/**
* write local IP address - %A
*/
protected static class LocalAddrElement implements AccessLogElement {
private final String localAddrValue;
public LocalAddrElement(boolean ipv6Canonical) {
String init;
try {
init = InetAddress.getLocalHost().getHostAddress();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
init = "127.0.0.1";
}
if (ipv6Canonical) {
localAddrValue = IPv6Utils.canonize(init);
} else {
localAddrValue = init;
}
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
buf.append(localAddrValue);
}
}
/**
* write remote IP address - %a
*/
protected class RemoteAddrElement implements AccessLogElement, CachedElement {
/**
* Type of address to log
*/
private static final String remoteAddress = "remote";
private static final String peerAddress = "peer";
private final RemoteAddressType remoteAddressType;
public RemoteAddrElement() {
remoteAddressType = RemoteAddressType.REMOTE;
}
public RemoteAddrElement(String type) {
switch (type) {
case remoteAddress:
remoteAddressType = RemoteAddressType.REMOTE;
break;
case peerAddress:
remoteAddressType = RemoteAddressType.PEER;
break;
default:
log.error(sm.getString("accessLogValve.invalidRemoteAddressType", type));
remoteAddressType = RemoteAddressType.REMOTE;
break;
}
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
String value = null;
if (remoteAddressType == RemoteAddressType.PEER) {
value = request.getPeerAddr();
} else {
if (requestAttributesEnabled) {
Object addr = request.getAttribute(REMOTE_ADDR_ATTRIBUTE);
if (addr == null) {
value = request.getRemoteAddr();
} else {
value = addr.toString();
}
} else {
value = request.getRemoteAddr();
}
}
if (ipv6Canonical) {
value = IPv6Utils.canonize(value);
}
buf.append(value);
}
@Override
public void cache(Request request) {
if (!requestAttributesEnabled) {
if (remoteAddressType == RemoteAddressType.PEER) {
request.getPeerAddr();
} else {
request.getRemoteAddr();
}
}
}
}
/**
* write remote host name - %h
*/
protected class HostElement implements AccessLogElement, CachedElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
String value = null;
if (requestAttributesEnabled) {
Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE);
if (host != null) {
value = host.toString();
}
}
if (value == null || value.length() == 0) {
value = request.getRemoteHost();
}
if (value == null || value.length() == 0) {
value = "-";
}
if (ipv6Canonical) {
value = IPv6Utils.canonize(value);
}
buf.append(value);
}
@Override
public void cache(Request request) {
if (!requestAttributesEnabled) {
request.getRemoteHost();
}
}
}
/**
* write remote logical username from identd (always returns '-') - %l
*/
protected static class LogicalUserNameElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
buf.append('-');
}
}
/**
* write request protocol - %H
*/
protected class ProtocolElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (requestAttributesEnabled) {
Object proto = request.getAttribute(PROTOCOL_ATTRIBUTE);
if (proto == null) {
buf.append(request.getProtocol());
} else {
buf.append(proto.toString());
}
} else {
buf.append(request.getProtocol());
}
}
}
/**
* write remote user that was authenticated (if any), else '-' - %u
*/
protected static class UserElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (request != null) {
String value = request.getRemoteUser();
if (value != null) {
escapeAndAppend(value, buf);
} else {
buf.append('-');
}
} else {
buf.append('-');
}
}
}
/**
* write date and time, in configurable format (default CLF) - %t or %{format}t
*/
protected class DateAndTimeElement implements AccessLogElement {
/**
* Format prefix specifying request start time
*/
private static final String requestStartPrefix = "begin";
/**
* Format prefix specifying response end time
*/
private static final String responseEndPrefix = "end";
/**
* Separator between optional prefix and rest of format
*/
private static final String prefixSeparator = ":";
/**
* Special format for seconds since epoch
*/
private static final String secFormat = "sec";
/**
* Special format for milliseconds since epoch
*/
private static final String msecFormat = "msec";
/**
* Special format for millisecond part of timestamp
*/
private static final String msecFractionFormat = "msec_frac";
/**
* The patterns we use to replace "S" and "SSS" millisecond formatting of SimpleDateFormat by our own handling
*/
private static final String msecPattern = "{#}";
private static final String tripleMsecPattern = msecPattern + msecPattern + msecPattern;
/* Our format description string, null if CLF */
private final String format;
/* Does the format string contain characters we need to escape */
private final boolean needsEscaping;
/* Whether to use begin of request or end of response as the timestamp */
private final boolean usesBegin;
/* The format type */
private final FormatType type;
/* Whether we need to postprocess by adding milliseconds */
private boolean usesMsecs = false;
protected DateAndTimeElement() {
this(null);
}
/**
* Replace the millisecond formatting character 'S' by some dummy characters in order to make the resulting
* formatted time stamps cacheable. We replace the dummy chars later with the actual milliseconds because that's
* relatively cheap.
*/
private String tidyFormat(String format) {
boolean escape = false;
StringBuilder result = new StringBuilder();
int len = format.length();
char x;
for (int i = 0; i < len; i++) {
x = format.charAt(i);
if (escape || x != 'S') {
result.append(x);
} else {
result.append(msecPattern);
usesMsecs = true;
}
if (x == '\'') {
escape = !escape;
}
}
return result.toString();
}
protected DateAndTimeElement(String sdf) {
String format = sdf;
boolean needsEscaping = false;
if (sdf != null) {
CharArrayWriter writer = new CharArrayWriter();
escapeAndAppend(sdf, writer);
String escaped = writer.toString();
if (!escaped.equals(sdf)) {
needsEscaping = true;
}
}
this.needsEscaping = needsEscaping;
boolean usesBegin = false;
FormatType type = FormatType.CLF;
if (format != null) {
if (format.equals(requestStartPrefix)) {
usesBegin = true;
format = "";
} else if (format.startsWith(requestStartPrefix + prefixSeparator)) {
usesBegin = true;
format = format.substring(6);
} else if (format.equals(responseEndPrefix)) {
usesBegin = false;
format = "";
} else if (format.startsWith(responseEndPrefix + prefixSeparator)) {
usesBegin = false;
format = format.substring(4);
}
if (format.length() == 0) {
type = FormatType.CLF;
} else if (format.equals(secFormat)) {
type = FormatType.SEC;
} else if (format.equals(msecFormat)) {
type = FormatType.MSEC;
} else if (format.equals(msecFractionFormat)) {
type = FormatType.MSEC_FRAC;
} else {
type = FormatType.SDF;
format = tidyFormat(format);
}
}
this.format = format;
this.usesBegin = usesBegin;
this.type = type;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
Instant requestStartInstant = Instant.from(request.getCoyoteRequest().getStartInstant());
long frac;
if (!usesBegin) {
requestStartInstant = requestStartInstant.plusNanos(time);
}
/*
* Implementation note: This is deliberately not implemented using switch. If a switch is used the compiler
* (at least the Oracle one) will use a synthetic class to implement the switch. The problem is that this
* class needs to be pre-loaded when using a SecurityManager and the name of that class will depend on any
* anonymous inner classes and any other synthetic classes. As such the name is not constant and keeping the
* pre-loading up to date as the name changes is error prone.
*/
if (type == FormatType.CLF) {
buf.append(localDateCache.get().getFormat(requestStartInstant.toEpochMilli()));
} else if (type == FormatType.SEC) {
buf.append(Long.toString(requestStartInstant.getEpochSecond()));
} else if (type == FormatType.MSEC) {
buf.append(Long.toString(requestStartInstant.toEpochMilli()));
} else if (type == FormatType.MSEC_FRAC) {
frac = requestStartInstant.toEpochMilli() % 1000;
if (frac < 100) {
if (frac < 10) {
buf.append('0');
buf.append('0');
} else {
buf.append('0');
}
}
buf.append(Long.toString(frac));
} else {
// FormatType.SDF
long timestamp = requestStartInstant.toEpochMilli();
String temp = localDateCache.get().getFormat(format, locale, timestamp);
if (usesMsecs) {
frac = timestamp % 1000;
StringBuilder tripleMsec = new StringBuilder(4);
if (frac < 100) {
tripleMsec.append('0');
if (frac < 10) {
tripleMsec.append('0');
}
}
tripleMsec.append(frac);
temp = temp.replace(tripleMsecPattern, tripleMsec);
temp = temp.replace(msecPattern, Long.toString(frac));
}
if (needsEscaping) {
escapeAndAppend(temp, buf);
} else {
buf.append(temp);
}
}
}
}
/**
* write first line of the request (method and request URI) - %r
*/
protected static class RequestElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (request != null) {
String method = request.getMethod();
if (method == null) {
// No method means no request line
buf.append('-');
} else {
buf.append(request.getMethod());
buf.append(' ');
buf.append(request.getRequestURI());
if (request.getQueryString() != null) {
buf.append('?');
buf.append(request.getQueryString());
}
buf.append(' ');
buf.append(request.getProtocol());
}
} else {
buf.append('-');
}
}
}
/**
* write HTTP status code of the response - %s
*/
protected static class HttpStatusCodeElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (response != null) {
// This approach is used to reduce GC from toString conversion
int status = response.getStatus();
if (100 <= status && status < 1000) {
buf.append((char) ('0' + (status / 100))).append((char) ('0' + ((status / 10) % 10)))
.append((char) ('0' + (status % 10)));
} else {
buf.append(Integer.toString(status));
}
} else {
buf.append('-');
}
}
}
/**
* write local or remote port for request connection - %p and %{xxx}p
*/
protected class PortElement implements AccessLogElement, CachedElement {
/**
* Type of port to log
*/
private static final String localPort = "local";
private static final String remotePort = "remote";
private final PortType portType;
public PortElement() {
portType = PortType.LOCAL;
}
public PortElement(String type) {
switch (type) {
case remotePort:
portType = PortType.REMOTE;
break;
case localPort:
portType = PortType.LOCAL;
break;
default:
log.error(sm.getString("accessLogValve.invalidPortType", type));
portType = PortType.LOCAL;
break;
}
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (requestAttributesEnabled && portType == PortType.LOCAL) {
Object port = request.getAttribute(SERVER_PORT_ATTRIBUTE);
if (port == null) {
buf.append(Integer.toString(request.getServerPort()));
} else {
buf.append(port.toString());
}
} else {
if (portType == PortType.LOCAL) {
buf.append(Integer.toString(request.getServerPort()));
} else {
buf.append(Integer.toString(request.getRemotePort()));
}
}
}
@Override
public void cache(Request request) {
if (portType == PortType.REMOTE) {
request.getRemotePort();
}
}
}
/**
* write bytes sent, excluding HTTP headers - %b, %B
*/
protected static class ByteSentElement implements AccessLogElement {
private final boolean conversion;
/**
* @param conversion <code>true</code> to write '-' instead of 0 - %b.
*/
public ByteSentElement(boolean conversion) {
this.conversion = conversion;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
// Don't need to flush since trigger for log message is after the
// response has been committed
long length = response.getBytesWritten(false);
if (length <= 0) {
// Protect against nulls and unexpected types as these values
// may be set by untrusted applications
Object start = request.getAttribute(Globals.SENDFILE_FILE_START_ATTR);
if (start instanceof Long) {
Object end = request.getAttribute(Globals.SENDFILE_FILE_END_ATTR);
if (end instanceof Long) {
length = ((Long) end).longValue() - ((Long) start).longValue();
}
}
}
if (length <= 0 && conversion) {
buf.append('-');
} else {
buf.append(Long.toString(length));
}
}
}
/**
* write request method (GET, POST, etc.) - %m
*/
protected static class MethodElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (request != null) {
buf.append(request.getMethod());
}
}
}
/**
* write time taken to process the request - %D, %T
*/
protected static class ElapsedTimeElement implements AccessLogElement {
public enum Style {
SECONDS {
@Override
public void append(CharArrayWriter buf, long time) {
buf.append(Long.toString(TimeUnit.NANOSECONDS.toSeconds(time)));
}
},
SECONDS_FRACTIONAL {
@Override
public void append(CharArrayWriter buf, long time) {
time = time / 1000000; // Convert to millis
buf.append(Long.toString(time / 1000));
buf.append('.');
int remains = (int) (time % 1000);
buf.append(Long.toString(remains / 100));
remains = remains % 100;
buf.append(Long.toString(remains / 10));
buf.append(Long.toString(remains % 10));
}
},
MILLISECONDS {
@Override
public void append(CharArrayWriter buf, long time) {
buf.append(Long.toString(TimeUnit.NANOSECONDS.toMillis(time)));
}
},
MICROSECONDS {
@Override
public void append(CharArrayWriter buf, long time) {
buf.append(Long.toString(TimeUnit.NANOSECONDS.toMicros(time)));
}
},
NANOSECONDS {
@Override
public void append(CharArrayWriter buf, long time) {
buf.append(Long.toString(time));
}
};
/**
* Append the time to the buffer in the appropriate format.
*
* @param buf The buffer to append to.
* @param time The time to log in nanoseconds.
*/
public abstract void append(CharArrayWriter buf, long time);
}
private final Style style;
/**
* Creates a new ElapsedTimeElement that will log the time in the specified style.
*
* @param style The elapsed-time style to use.
*/
public ElapsedTimeElement(Style style) {
this.style = style;
}
/**
* @param micros <code>true</code>, write time in microseconds - %D
* @param millis <code>true</code>, write time in milliseconds, if both arguments are <code>false</code>, write
* time in seconds - %T
*/
public ElapsedTimeElement(boolean micros, boolean millis) {
this(micros ? Style.MICROSECONDS : millis ? Style.MILLISECONDS : Style.SECONDS);
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
style.append(buf, time);
}
}
/**
* write time until first byte is written (commit time) in millis - %F
*/
protected static class FirstByteTimeElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
long commitTime = response.getCoyoteResponse().getCommitTimeNanos();
if (commitTime == -1) {
buf.append('-');
} else {
long delta = commitTime - request.getCoyoteRequest().getStartTimeNanos();
buf.append(Long.toString(TimeUnit.NANOSECONDS.toMillis(delta)));
}
}
}
/**
* write Query string (prepended with a '?' if it exists) - %q
*/
protected static class QueryElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
String query = null;
if (request != null) {
query = request.getQueryString();
}
if (query != null) {
buf.append('?');
buf.append(query);
}
}
}
/**
* write user session ID - %S
*/
protected static class SessionIdElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (request == null) {
buf.append('-');
} else {
Session session = request.getSessionInternal(false);
if (session == null) {
buf.append('-');
} else {
buf.append(session.getIdInternal());
}
}
}
}
/**
* write requested URL path - %U
*/
protected static class RequestURIElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (request != null) {
buf.append(request.getRequestURI());
} else {
buf.append('-');
}
}
}
/**
* write local server name - %v
*/
protected class LocalServerNameElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
String value = null;
if (requestAttributesEnabled) {
Object serverName = request.getAttribute(SERVER_NAME_ATTRIBUTE);
if (serverName != null) {
value = serverName.toString();
}
}
if (value == null || value.length() == 0) {
value = request.getServerName();
}
if (value == null || value.length() == 0) {
value = "-";
}
if (ipv6Canonical) {
value = IPv6Utils.canonize(value);
}
buf.append(value);
}
}
/**
* write any string
*/
protected static class StringElement implements AccessLogElement {
private final String str;
public StringElement(String str) {
this.str = str;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
buf.append(str);
}
}
/**
* write incoming headers - %{xxx}i
*/
protected static class HeaderElement implements AccessLogElement {
private final String header;
public HeaderElement(String header) {
this.header = header;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
Enumeration<String> iter = request.getHeaders(header);
if (iter.hasMoreElements()) {
escapeAndAppend(iter.nextElement(), buf);
while (iter.hasMoreElements()) {
buf.append(',');
escapeAndAppend(iter.nextElement(), buf);
}
return;
}
buf.append('-');
}
}
/**
* write a specific cookie - %{xxx}c
*/
protected static class CookieElement implements AccessLogElement {
private final String cookieNameToLog;
public CookieElement(String cookieNameToLog) {
this.cookieNameToLog = cookieNameToLog;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
StringBuilder value = null;
boolean first = true;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieNameToLog.equals(cookie.getName())) {
if (value == null) {
value = new StringBuilder();
}
if (first) {
first = false;
} else {
value.append(',');
}
value.append(cookie.getValue());
}
}
}
if (value == null) {
buf.append('-');
} else {
escapeAndAppend(value.toString(), buf);
}
}
}
/**
* write a specific response header - %{xxx}o
*/
protected static class ResponseHeaderElement implements AccessLogElement {
private final String header;
public ResponseHeaderElement(String header) {
this.header = header;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (null != response) {
Iterator<String> iter = response.getHeaders(header).iterator();
if (iter.hasNext()) {
escapeAndAppend(iter.next(), buf);
while (iter.hasNext()) {
buf.append(',');
escapeAndAppend(iter.next(), buf);
}
return;
}
}
buf.append('-');
}
}
/**
* write an attribute in the ServletRequest - %{xxx}r
*/
protected static class RequestAttributeElement implements AccessLogElement {
private final String attribute;
public RequestAttributeElement(String attribute) {
this.attribute = attribute;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
Object value = null;
if (request != null) {
value = request.getAttribute(attribute);
} else {
value = "??";
}
if (value != null) {
if (value instanceof String) {
escapeAndAppend((String) value, buf);
} else {
escapeAndAppend(value.toString(), buf);
}
} else {
buf.append('-');
}
}
}
/**
* write an attribute in the HttpSession - %{xxx}s
*/
protected static class SessionAttributeElement implements AccessLogElement {
private final String attribute;
public SessionAttributeElement(String attribute) {
this.attribute = attribute;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
Object value = null;
if (null != request) {
HttpSession sess = request.getSession(false);
if (null != sess) {
value = sess.getAttribute(attribute);
}
} else {
value = "??";
}
if (value != null) {
if (value instanceof String) {
escapeAndAppend((String) value, buf);
} else {
escapeAndAppend(value.toString(), buf);
}
} else {
buf.append('-');
}
}
}
/**
* Write connection status when response is completed - %X
*/
protected static class ConnectionStatusElement implements AccessLogElement {
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
if (response != null && request != null) {
boolean statusFound = false;
// Check whether connection IO is in "not allowed" state
AtomicBoolean isIoAllowed = new AtomicBoolean(false);
request.getCoyoteRequest().action(ActionCode.IS_IO_ALLOWED, isIoAllowed);
if (!isIoAllowed.get()) {
buf.append('X');
statusFound = true;
} else {
// Check for connection aborted cond
if (response.isError()) {
Throwable ex = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
if (ex instanceof ClientAbortException) {
buf.append('X');
statusFound = true;
}
}
}
// If status is not found yet, cont to check whether connection is keep-alive or close
if (!statusFound) {
String connStatus = response.getHeader(org.apache.coyote.http11.Constants.CONNECTION);
if (org.apache.coyote.http11.Constants.CLOSE.equalsIgnoreCase(connStatus)) {
buf.append('-');
} else {
buf.append('+');
}
}
} else {
// Unknown connection status
buf.append('?');
}
}
}
/**
* Write identifier element %{xxx}L
*/
protected static class IdentifierElement implements AccessLogElement {
/**
* Type of identifier to log
*/
private final IdentifierType identifierType;
public IdentifierElement() {
this("");
}
public IdentifierElement(String type) {
switch (type) {
case "c":
identifierType = IdentifierType.CONNECTION;
break;
default:
log.error(sm.getString("accessLogValve.invalidIdentifierType", type));
identifierType = IdentifierType.UNKNOWN;
break;
}
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
switch (identifierType) {
case CONNECTION:
buf.append(request.getServletConnection().getConnectionId());
break;
case UNKNOWN:
buf.append("???");
}
}
}
/**
* Parse pattern string and create the array of AccessLogElement.
*
* @return the log elements array
*/
protected AccessLogElement[] createLogElements() {
List<AccessLogElement> list = new ArrayList<>();
boolean replace = false;
StringBuilder buf = new StringBuilder();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
if (replace) {
/*
* For code that processes {, the behavior will be ... if I do not encounter a closing } - then I ignore
* the {
*/
if ('{' == ch) {
StringBuilder name = new StringBuilder();
int j = i + 1;
for (; j < pattern.length() && '}' != pattern.charAt(j); j++) {
name.append(pattern.charAt(j));
}
if (j + 1 < pattern.length()) {
/* the +1 was to account for } which we increment now */
j++;
list.add(createAccessLogElement(name.toString(), pattern.charAt(j)));
i = j; /* Since we walked more than one character */
} else {
// D'oh - end of string - pretend we never did this
// and do processing the "old way"
list.add(createAccessLogElement(ch));
}
} else {
list.add(createAccessLogElement(ch));
}
replace = false;
} else if (ch == '%') {
replace = true;
list.add(new StringElement(buf.toString()));
buf = new StringBuilder();
} else {
buf.append(ch);
}
}
if (buf.length() > 0) {
list.add(new StringElement(buf.toString()));
}
return list.toArray(new AccessLogElement[0]);
}
private CachedElement[] createCachedElements(AccessLogElement[] elements) {
List<CachedElement> list = new ArrayList<>();
for (AccessLogElement element : elements) {
if (element instanceof CachedElement) {
list.add((CachedElement) element);
}
}
return list.toArray(new CachedElement[0]);
}
/**
* Create an AccessLogElement implementation which needs an element name.
*
* @param name Header name
* @param pattern char in the log pattern
*
* @return the log element
*/
protected AccessLogElement createAccessLogElement(String name, char pattern) {
switch (pattern) {
case 'a':
return new RemoteAddrElement(name);
case 'c':
return new CookieElement(name);
case 'i':
return new HeaderElement(name);
case 'L':
return new IdentifierElement(name);
case 'o':
return new ResponseHeaderElement(name);
case 'p':
return new PortElement(name);
case 'r':
if (TLSUtil.isTLSRequestAttribute(name)) {
tlsAttributeRequired = true;
}
return new RequestAttributeElement(name);
case 's':
return new SessionAttributeElement(name);
case 't':
return new DateAndTimeElement(name);
case 'T':
// ms for milliseconds, us for microseconds, and s for seconds
if ("ns".equals(name)) {
return new ElapsedTimeElement(ElapsedTimeElement.Style.NANOSECONDS);
} else if ("us".equals(name)) {
return new ElapsedTimeElement(ElapsedTimeElement.Style.MICROSECONDS);
} else if ("ms".equals(name)) {
return new ElapsedTimeElement(ElapsedTimeElement.Style.MILLISECONDS);
} else if ("fracsec".equals(name)) {
return new ElapsedTimeElement(ElapsedTimeElement.Style.SECONDS_FRACTIONAL);
} else {
return new ElapsedTimeElement(false, false);
}
default:
return new StringElement("???");
}
}
/**
* Create an AccessLogElement implementation.
*
* @param pattern char in the log pattern
*
* @return the log element
*/
protected AccessLogElement createAccessLogElement(char pattern) {
switch (pattern) {
case 'a':
return new RemoteAddrElement();
case 'A':
return new LocalAddrElement(ipv6Canonical);
case 'b':
return new ByteSentElement(true);
case 'B':
return new ByteSentElement(false);
case 'D':
return new ElapsedTimeElement(true, false);
case 'F':
return new FirstByteTimeElement();
case 'h':
return new HostElement();
case 'H':
return new ProtocolElement();
case 'l':
return new LogicalUserNameElement();
case 'm':
return new MethodElement();
case 'p':
return new PortElement();
case 'q':
return new QueryElement();
case 'r':
return new RequestElement();
case 's':
return new HttpStatusCodeElement();
case 'S':
return new SessionIdElement();
case 't':
return new DateAndTimeElement();
case 'T':
return new ElapsedTimeElement(false, false);
case 'u':
return new UserElement();
case 'U':
return new RequestURIElement();
case 'v':
return new LocalServerNameElement();
case 'I':
return new ThreadNameElement();
case 'X':
return new ConnectionStatusElement();
default:
return new StringElement("???" + pattern + "???");
}
}
/*
* This method is intended to mimic the escaping performed by httpd and mod_log_config. mod_log_config escapes more
* elements than indicated by the documentation. See:
* https://github.com/apache/httpd/blob/trunk/modules/loggers/mod_log_config.c
*
* The following escaped elements are not supported by Tomcat: - %C cookie value (see %{}c below) - %e environment
* variable - %f filename - %l remote logname (always logs "-") - %n note - %R handler - %ti trailer request header
* - %to trailer response header - %V server name per UseCanonicalName setting
*
* The following escaped elements are not escaped in Tomcat because values that would require escaping are rejected
* before they reach the AccessLogValve: - %h remote host - %H request protocol - %m request method - %q query
* string - %r request line - %U request URI - %v canonical server name
*
* The following escaped elements are supported by Tomcat: - %{}i request header - %{}o response header - %u remote
* user
*
* The following additional Tomcat elements are escaped for consistency: - %{}c cookie value - %{}r request
* attribute - %{}s session attribute
*
* giving a total of 6 elements that are escaped in Tomcat.
*
* Quoting from the httpd docs: "...non-printable and other special characters in %r, %i and %o are escaped using
* \xhh sequences, where hh stands for the hexadecimal representation of the raw byte. Exceptions from this rule are
* " and \, which are escaped by prepending a backslash, and all whitespace characters, which are written in their
* C-style notation (\n, \t, etc)."
*
* Reviewing the httpd code, characters with the high bit set are escaped. The httpd is assuming a single byte
* encoding which may not be true for Tomcat so Tomcat uses the Java \\uXXXX encoding.
*/
protected static void escapeAndAppend(String input, CharArrayWriter dest) {
escapeAndAppend(input, dest, false);
}
protected static void escapeAndAppend(String input, CharArrayWriter dest, boolean escapeQuoteAsDouble) {
if (input == null || input.isEmpty()) {
dest.append('-');
return;
}
int len = input.length();
// As long as we don't encounter chars that need escaping,
// we only remember start and length of that string part.
// "next" is the start of the string part containing these chars,
// "current - 1" is its end. So writing from "next" with length
// "current - next" writes that part.
// We write that part whenever we find a character to escape and the
// unchanged and unwritten string part is not empty.
int next = 0;
char c;
for (int current = 0; current < len; current++) {
c = input.charAt(current);
// Fast path
if (c >= 32 && c < 127) {
// special case " and \
switch (c) {
case '\\': // dec 92
// Write unchanged string parts
if (current > next) {
dest.write(input, next, current - next);
}
next = current + 1;
dest.append("\\\\");
break;
case '\"': // dec 34
// Write unchanged string parts
if (current > next) {
dest.write(input, next, current - next);
}
next = current + 1;
if (escapeQuoteAsDouble) {
dest.append("\"\"");
} else {
dest.append("\\\"");
}
break;
// Don't output individual unchanged chars,
// write the sub string only when the first char to encode
// is encountered plus at the end.
default:
}
// Control (1-31), delete (127) or above 127
} else {
// Write unchanged string parts
if (current > next) {
dest.write(input, next, current - next);
}
next = current + 1;
switch (c) {
// Standard escapes for some control chars
case '\f': // dec 12
dest.append("\\f");
break;
case '\n': // dec 10
dest.append("\\n");
break;
case '\r': // dec 13
dest.append("\\r");
break;
case '\t': // dec 09
dest.append("\\t");
break;
// Unicode escape \\uXXXX
default:
dest.append("\\u");
dest.append(HexUtils.toHexString(c));
}
}
}
// Write remaining unchanged string parts
if (len > next) {
dest.write(input, next, len - next);
}
}
}
|