Datasets:
File size: 117,775 Bytes
0e239c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 | diff --git a/.changelog/5266.added b/.changelog/5266.added
new file mode 100644
index 00000000..66f88e9f
--- /dev/null
+++ b/.changelog/5266.added
@@ -0,0 +1 @@
+`opentelemetry-api`, `opentelemetry-sdk`: add support for extended attribute values everywhere.
\ No newline at end of file
diff --git a/.changelog/5266.changed b/.changelog/5266.changed
new file mode 100644
index 00000000..dbb19eb7
--- /dev/null
+++ b/.changelog/5266.changed
@@ -0,0 +1,2 @@
+The public `opentelemetry.util.types.AttributeValue` type in package `opentelemetry-api` is being expanded to include `None`, heterogeneous sequences of primitive types (and nested sequences) as opposed to only homogeneous primitive sequences, and Mappings of strings to any primitive types or sequences/mappings (which themselves must only contain primitive types or sequences/mappings validated the same way).
+If a `bytes` type is set as an attribute value in the SDK, it will no longer be utf-8 decoded to a string, instead it will be passed along as is in accordance with the OTEL spec, since `bytes` is a valid type in the OTLP proto.
\ No newline at end of file
diff --git a/docs/conf.py b/docs/conf.py
index e0058937..20d53cd2 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -26,14 +26,17 @@ from django.conf import settings
settings.configure()
-# Provide AnyValue in opentelemetry.attributes module's namespace so the
-# "AnyValue" forward reference in opentelemetry.util.types._ExtendedAttributes
-# resolves when sphinx_autodoc_typehints calls typing.get_type_hints() on
-# BoundedAttributes (whose __globals__ is the attributes module). Docs-only.
-import opentelemetry.attributes # noqa: E402
-from opentelemetry.util.types import AnyValue as _AnyValue # noqa: E402
+# Docs-only: resolves the "AnyValue" forward reference wherever
+# get_type_hints() evaluates it. AnyValue is a recursive alias, so
+# modules that import it only under TYPE_CHECKING hit a NameError.
+# TODO: https://github.com/open-telemetry/opentelemetry-python/issues/5304
+# this can be removed by importing AnyValue at runtime in the
+# modules that annotate with it
+import builtins # noqa: E402
-opentelemetry.attributes.AnyValue = _AnyValue
+from opentelemetry.util.types import AnyValue # noqa: E402
+
+builtins.AnyValue = AnyValue
source_dirs = [
@@ -179,10 +182,6 @@ nitpick_ignore = [
"py:class",
"AnyValue",
),
- (
- "py:class",
- "_ExtendedAttributes",
- ),
("py:class", "Token"),
# ``from os import PathLike`` renders as the bare name ``PathLike`` in the
# file exporter type hints, which sphinx cannot resolve to os.PathLike.
diff --git a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py
index f293ae99..017c8aa3 100644
--- a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py
+++ b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py
@@ -25,7 +25,7 @@ from opentelemetry.proto_json.resource.v1.resource import (
)
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.util.instrumentation import InstrumentationScope
-from opentelemetry.util.types import _ExtendedAttributes
+from opentelemetry.util.types import Attributes
_logger = logging.getLogger(__name__)
@@ -84,7 +84,7 @@ def _encode_trace_id(trace_id: int) -> bytes:
def _encode_attributes(
- attributes: _ExtendedAttributes | None,
+ attributes: Attributes,
) -> list[JSONKeyValue]:
if not attributes:
return []
diff --git a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py
index 6b3ab356..1dee399d 100644
--- a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py
+++ b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py
@@ -50,9 +50,7 @@ def _encode_log(readable_log_record: ReadableLogRecord) -> JSONLogRecord:
flags=int(readable_log_record.log_record.trace_flags),
body=_encode_value(readable_log_record.log_record.body),
severity_text=readable_log_record.log_record.severity_text,
- attributes=_encode_attributes(
- cast(Attributes, readable_log_record.log_record.attributes),
- ),
+ attributes=_encode_attributes(cast(Attributes, readable_log_record.log_record.attributes)),
dropped_attributes_count=readable_log_record.dropped_attributes,
severity_number=getattr(readable_log_record.log_record.severity_number, "value", None),
event_name=readable_log_record.log_record.event_name,
diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py
index 720334c9..1524e1dc 100644
--- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py
+++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py
@@ -35,7 +35,7 @@ if TYPE_CHECKING:
from typing import Literal
from urllib.parse import ParseResult as UrlParseResult
- from opentelemetry.util.types import Attributes, AttributeValue
+ from opentelemetry.util.types import AnyValue, Attributes
_component_counter = Counter()
@@ -84,7 +84,7 @@ class ExporterMetrics:
component_type_value = component_type.value if component_type else "unknown_otlp_exporter"
count = _component_counter[component_type_value]
_component_counter[component_type_value] = count + 1
- self._standard_attrs: dict[str, AttributeValue] = {
+ self._standard_attrs: dict[str, AnyValue] = {
OTEL_COMPONENT_TYPE: component_type_value,
OTEL_COMPONENT_NAME: f"{component_type_value}/{count}",
}
diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py
index a5541ff9..55895fc8 100644
--- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py
+++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py
@@ -27,7 +27,7 @@ from opentelemetry.proto.resource.v1.resource_pb2 import (
)
from opentelemetry.sdk.trace import Resource
from opentelemetry.sdk.util.instrumentation import InstrumentationScope
-from opentelemetry.util.types import _ExtendedAttributes
+from opentelemetry.util.types import Attributes
_logger = logging.getLogger(__name__)
@@ -85,9 +85,7 @@ def _encode_trace_id(trace_id: int) -> bytes:
return trace_id.to_bytes(length=16, byteorder="big", signed=False)
-def _encode_attributes(
- attributes: _ExtendedAttributes | None,
-) -> list[PB2KeyValue]:
+def _encode_attributes(attributes: Attributes) -> list[PB2KeyValue]:
if not attributes:
return []
pb2_attributes = []
diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py
index db583f69..b8ae543c 100644
--- a/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py
+++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py
@@ -30,7 +30,7 @@ class MockTraceServiceStub:
@patch(
- "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter._stub",
+ "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.TraceServiceStub",
new=MockTraceServiceStub,
)
def test_simple_span_processor(benchmark):
@@ -51,7 +51,7 @@ def test_simple_span_processor(benchmark):
@patch(
- "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter._stub",
+ "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.TraceServiceStub",
new=MockTraceServiceStub,
)
def test_batch_span_processor(benchmark):
diff --git a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py
index 5c129db8..80421fd7 100644
--- a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py
+++ b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py
@@ -105,7 +105,7 @@ from opentelemetry.sdk.util.instrumentation import InstrumentationScope
from opentelemetry.semconv._incubating.attributes.otel_attributes import (
OtelComponentTypeValues,
)
-from opentelemetry.util.types import Attributes, AttributeValue
+from opentelemetry.util.types import AnyValue, Attributes
_logger = getLogger(__name__)
@@ -372,8 +372,8 @@ class _CustomCollector:
def _translate_metric(
self,
metric: Metric,
- scope_attrs: dict[str, AttributeValue],
- resource_attrs: dict[str, AttributeValue],
+ scope_attrs: dict[str, AnyValue],
+ resource_attrs: dict[str, AnyValue],
metric_family_id_metric_family: dict[str, PrometheusMetric],
) -> None:
metric_name = self._resolve_metric_name(metric.name)
@@ -420,10 +420,10 @@ class _CustomCollector:
else:
_logger.warning("Unsupported metric data. %s", type(metric.data))
- def _build_scope_attrs(self, scope: InstrumentationScope) -> dict[str, AttributeValue]:
+ def _build_scope_attrs(self, scope: InstrumentationScope) -> dict[str, AnyValue]:
if not self._scope_info_enabled:
return {}
- attrs: dict[str, AttributeValue] = {}
+ attrs: dict[str, AnyValue] = {}
if scope.attributes:
for key, value in scope.attributes.items():
attrs[_OTEL_SCOPE_ATTR_PREFIX + key] = value
@@ -432,7 +432,7 @@ class _CustomCollector:
attrs[_OTEL_SCOPE_SCHEMA_URL_LABEL] = scope.schema_url or ""
return attrs
- def _build_resource_attrs(self, resource: Resource) -> dict[str, AttributeValue]:
+ def _build_resource_attrs(self, resource: Resource) -> dict[str, AnyValue]:
if not self._resource_attribute_filter:
return {}
return {key: value for key, value in resource.attributes.items() if self._resource_attribute_filter(key)}
@@ -445,8 +445,8 @@ class _CustomCollector:
def _collect_data_points(
self,
metric_data: DataT,
- scope_attrs: dict[str, AttributeValue],
- resource_attrs: dict[str, AttributeValue],
+ scope_attrs: dict[str, AnyValue],
+ resource_attrs: dict[str, AnyValue],
) -> tuple[list[str], list[list[str]], list[float | dict[str, Any]]]:
keys: set[str] = set()
rows: list[dict[str, str]] = []
diff --git a/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py b/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py
index cc90523c..207147bf 100644
--- a/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py
@@ -40,7 +40,7 @@ from opentelemetry.trace import get_current_span
from opentelemetry.trace.span import TraceFlags
from opentelemetry.util._once import Once
from opentelemetry.util._providers import _load_provider
-from opentelemetry.util.types import AnyValue, _ExtendedAttributes
+from opentelemetry.util.types import AnyValue, Attributes
_logger = getLogger(__name__)
@@ -63,7 +63,7 @@ class LogRecord(ABC):
severity_text: str | None = None,
severity_number: SeverityNumber | None = None,
body: AnyValue = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None: ...
@@ -83,7 +83,7 @@ class LogRecord(ABC):
severity_text: str | None = None,
severity_number: SeverityNumber | None = None,
body: AnyValue = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> None: ...
def __init__(
@@ -98,7 +98,7 @@ class LogRecord(ABC):
severity_text: str | None = None,
severity_number: SeverityNumber | None = None,
body: AnyValue = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None:
@@ -129,7 +129,7 @@ class Logger(ABC):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> None:
super().__init__()
self._name = name
@@ -147,7 +147,7 @@ class Logger(ABC):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None: ...
@@ -169,7 +169,7 @@ class Logger(ABC):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None:
@@ -192,7 +192,7 @@ class NoOpLogger(Logger):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None: ...
@@ -213,7 +213,7 @@ class NoOpLogger(Logger):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None:
@@ -226,7 +226,7 @@ class ProxyLogger(Logger):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
):
self._name = name
self._version = version
@@ -260,7 +260,7 @@ class ProxyLogger(Logger):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None: ...
@@ -281,7 +281,7 @@ class ProxyLogger(Logger):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None:
@@ -312,7 +312,7 @@ class LoggerProvider(ABC):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> Logger:
"""Returns a `Logger` for use by the given instrumentation library.
@@ -351,7 +351,7 @@ class NoOpLoggerProvider(LoggerProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> Logger:
"""Returns a NoOpLogger."""
return NoOpLogger(name, version=version, schema_url=schema_url, attributes=attributes)
@@ -363,7 +363,7 @@ class ProxyLoggerProvider(LoggerProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> Logger:
if _LOGGER_PROVIDER:
return _LOGGER_PROVIDER.get_logger(
@@ -426,7 +426,7 @@ def get_logger(
instrumenting_library_version: str = "",
logger_provider: LoggerProvider | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> Logger:
"""Returns a `Logger` for use within a python process.
diff --git a/opentelemetry-api/src/opentelemetry/attributes/__init__.py b/opentelemetry-api/src/opentelemetry/attributes/__init__.py
index c6715321..2ba2d393 100644
--- a/opentelemetry-api/src/opentelemetry/attributes/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/attributes/__init__.py
@@ -1,253 +1,160 @@
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0
+# pyright: reportUnnecessaryIsInstance=false
+
import copy
import logging
import threading
-from collections import OrderedDict
from collections.abc import Mapping, MutableMapping, Sequence
+from types import NoneType
+from typing import TYPE_CHECKING, Any, overload
+
+from typing_extensions import assert_never, deprecated
from opentelemetry.util import types
-# bytes are accepted as a user supplied value for attributes but
-# decoded to strings internally.
-_VALID_ATTR_VALUE_TYPES = (bool, str, bytes, int, float)
-# AnyValue possible values
-_VALID_ANY_VALUE_TYPES = (
- type(None),
- bool,
- bytes,
- int,
- float,
- str,
- Sequence,
- Mapping,
-)
-
-
-# TODO: Remove this workaround and revert to the simpler implementation
-# once Python 3.9 support is dropped (planned around May 2026).
-# This exists only to avoid issues caused by deprecated behavior in 3.9.
-def _type_name(t):
- return getattr(t, "__name__", getattr(t, "_name", repr(t)))
+_logger = logging.getLogger(__name__)
-_logger = logging.getLogger(__name__)
+# Calling str(x) will use an object's `__str__` method if it exists, otherwise it will use it's `__repr__` method.
+# If neither is defined it uses the base class's `object.__repr__` method, which returns a string that is hard to understand.
+# So in that case we drop the key/value pair.
+def _is_non_custom_str(key: Any) -> bool:
+ return type(key).__str__ is not object.__str__ or type(key).__repr__ is not object.__repr__
-# pylint: disable=too-many-return-statements
-# pylint: disable=too-many-branches
-def _clean_attribute(
- key: str, value: types.AttributeValue, max_len: int | None
-) -> types.AttributeValue | tuple[str | int | float, ...] | None:
- """Checks if attribute value is valid and cleans it if required.
+@overload
+def _clean_attribute_value(
+ value: Mapping[str, types.AnyValue],
+ max_string_value_length: int | None,
+) -> Mapping[str, types.AnyValue]: ...
- The function returns the cleaned value or None if the value is not valid.
- An attribute value is valid if it is either:
- - A primitive type: string, boolean, double precision floating
- point (IEEE 754-1985) or integer.
- - An array of primitive type values. The array MUST be homogeneous,
- i.e. it MUST NOT contain values of different types.
+@overload
+def _clean_attribute_value(
+ value: types.AnyValue,
+ max_string_value_length: int | None,
+) -> types.AnyValue: ...
- An attribute needs cleansing if:
- - Its length is greater than the maximum allowed length.
- - It needs to be encoded/decoded e.g, bytes to strings.
- """
- if not (key and isinstance(key, str)):
- _logger.warning("invalid key `%s`. must be non-empty string.", key)
- return None
-
- if isinstance(value, _VALID_ATTR_VALUE_TYPES):
- if isinstance(value, bytes):
- try:
- value = value.decode()
- except UnicodeDecodeError:
- _logger.warning("Byte attribute could not be decoded.")
- return None
- if max_len is not None and isinstance(value, str):
- value = value[:max_len]
- return value
+def _clean_attribute_value(
+ value: types.AnyValue,
+ max_string_value_length: int | None,
+) -> types.AnyValue:
+ """Recursively checks if an attribute value is valid and cleans it if required.
- if isinstance(value, Sequence):
- sequence_first_valid_type = None
- cleaned_seq = []
-
- for element in value:
- if isinstance(element, bytes):
- try:
- element = element.decode()
- except UnicodeDecodeError:
- _logger.warning("Byte attribute could not be decoded.")
- cleaned_seq.append(None)
- continue
- if max_len is not None and isinstance(element, str):
- element = element[:max_len]
- elif element is None:
- cleaned_seq.append(None)
- continue
+ String values are truncated to max_string_value_length if provided.
+ Anything that isn't of `types.AnyValue`, we attempt to cast to `str`.
+ If this fails, the value is replaced with None. Sequence's are converted to tuples and mappings
+ are copied into new dicts.
- element_type = type(element)
- # Reject attribute value if sequence contains a value with an incompatible type.
- if element_type not in _VALID_ATTR_VALUE_TYPES:
+ Returns:
+ The recursively cleaned AnyValue.
+ """
+ if isinstance(value, (NoneType, bool, int, float, bytes)):
+ return value
+ if isinstance(value, str):
+ if max_string_value_length is not None and len(value) > max_string_value_length:
+ _logger.warning(
+ "String attribute value exceeds max length of %d, truncating.",
+ max_string_value_length,
+ )
+ value = value[:max_string_value_length]
+ return value
+ if isinstance(value, Sequence):
+ return tuple(_clean_attribute_value(v, max_string_value_length) for v in value)
+ if isinstance(value, Mapping):
+ cleaned_mapping: dict[str, types.AnyValue] = {}
+ for key, val in value.items():
+ if not key:
_logger.warning(
- "Invalid type %s in attribute '%s' value sequence. Expected one of %s or None",
- element_type.__name__,
+ "invalid attribute key `%s`. must be non-empty string. Dropping key from attributes.",
key,
- [valid_type.__name__ for valid_type in _VALID_ATTR_VALUE_TYPES],
)
- return None
-
- # The type of the sequence must be homogeneous. The first non-None
- # element determines the type of the sequence
- if sequence_first_valid_type is None:
- sequence_first_valid_type = element_type
- # use equality instead of isinstance as isinstance(True, int) evaluates to True
- elif element_type != sequence_first_valid_type:
+ continue
+ # Spec says to convert unknown types to strings if possible (here and below too).
+ if not isinstance(key, str):
_logger.warning(
- "Attribute %r mixes types %s and %s in attribute value sequence",
+ "Invalid type `%s` for attribute key `%s`, must be a str. Key's `__str__/__repr__` method will be called if it exists, otherwise the key/value pair will be dropped.",
+ type(key),
key,
- sequence_first_valid_type.__name__,
- type(element).__name__,
)
- return None
-
- cleaned_seq.append(element)
-
- # Freeze mutable sequences defensively
- return tuple(cleaned_seq)
-
+ if _is_non_custom_str(key):
+ key = str(key)
+ else:
+ continue
+ cleaned_mapping[key] = _clean_attribute_value(val, max_string_value_length)
+ return cleaned_mapping
+ if TYPE_CHECKING:
+ assert_never(value)
_logger.warning(
- "Invalid type %s for attribute '%s' value. Expected one of %s or a sequence of those types",
- type(value).__name__,
- key,
- [valid_type.__name__ for valid_type in _VALID_ATTR_VALUE_TYPES],
+ "Invalid type `%s` for attribute value. Expected one of bool, str, None, bytes, int, float or a "
+ "Mapping or Sequence of those types. Value's __str__ method will be called if it exists, otherwise the value will be replaced with None.",
+ type(value),
)
- return None
-
-
-def _clean_extended_attribute_value( # pylint: disable=too-many-branches
- value: types.AnyValue, max_len: int | None
-) -> types.AnyValue:
- # for primitive types just return the value and eventually shorten the string length
- if value is None or isinstance(value, _VALID_ATTR_VALUE_TYPES):
- if max_len is not None and isinstance(value, str):
- value = value[:max_len]
- return value
-
- if isinstance(value, Mapping):
- cleaned_dict: dict[str, types.AnyValue] = {}
- for key, element in value.items():
- # skip invalid keys
- if not (key and isinstance(key, str)):
- _logger.warning("invalid key `%s`. must be non-empty string.", key)
- continue
-
- cleaned_dict[key] = _clean_extended_attribute(key=key, value=element, max_len=max_len)
-
- return cleaned_dict
-
- if isinstance(value, Sequence):
- sequence_first_valid_type = None
- cleaned_seq: list[types.AnyValue] = []
-
- for element in value:
- if element is None:
- cleaned_seq.append(element)
- continue
-
- if max_len is not None and isinstance(element, str):
- element = element[:max_len]
-
- element_type = type(element)
- if element_type not in _VALID_ATTR_VALUE_TYPES:
- element = _clean_extended_attribute_value(element, max_len=max_len)
- element_type = type(element) # type: ignore
-
- # The type of the sequence must be homogeneous. The first non-None
- # element determines the type of the sequence
- if sequence_first_valid_type is None:
- sequence_first_valid_type = element_type
- # use equality instead of isinstance as isinstance(True, int) evaluates to True
- elif element_type != sequence_first_valid_type:
- _logger.warning(
- "Mixed types %s and %s in attribute value sequence",
- sequence_first_valid_type.__name__,
- type(element).__name__,
- )
- return None
-
- cleaned_seq.append(element)
-
- # Freeze mutable sequences defensively
- return tuple(cleaned_seq)
-
- # Some applications such as Django add values to log records whose types fall outside the
- # primitive types and `_VALID_ANY_VALUE_TYPES`, i.e., they are not of type `AnyValue`.
- # Rather than attempt to whitelist every possible instrumentation, we stringify those values here
- # so they can still be represented as attributes, falling back to the original TypeError only if
- # converting to string raises.
- try:
+ if _is_non_custom_str(value):
return str(value)
- except Exception:
- raise TypeError(
- f"Invalid type {type(value).__name__} for attribute value. "
- f"Expected one of {[_type_name(valid_type) for valid_type in _VALID_ANY_VALUE_TYPES]} or a "
- "sequence of those types",
- )
+ return None
-def _clean_extended_attribute(key: str, value: types.AnyValue, max_len: int | None) -> types.AnyValue:
- """Checks if attribute value is valid and cleans it if required.
+class BoundedAttributes(MutableMapping[str, types.AnyValue]):
+ """A dict with a fixed max capacity which cleans and potentially drops values to ensure they are valid attribute values.
- The function returns the cleaned value or None if the value is not valid.
+ Args:
+ maxlen: The maximum number of attributes to store, use None for no limit.
+ attributes: The initial attributes to store.
+ immutable: Defaults to true. Whether to allow adding/removing of attributes after the initialisation of the instance.
+ max_value_len: The maximum length of string values, use None for no limit.
+ extended_attributes: Deprecated. Kept for backwards compatibility. Extended attributes are now always used for attributes everywhere.
- An attribute value is valid if it is an AnyValue.
- An attribute needs cleansing if:
- - Its length is greater than the maximum allowed length.
+ When the dict is full and a new element is added, the oldest element is dropped. Attributes are made to be immutable when set in this container.
+ So passing a mutable list as an attribute value, and then mutating it after will not change it's value in this container.
"""
- if not (key and isinstance(key, str)):
- _logger.warning("invalid key `%s`. must be non-empty string.", key)
- return None
-
- try:
- return _clean_extended_attribute_value(value, max_len=max_len)
- except TypeError as exception:
- _logger.warning("Attribute %s: %s", key, exception)
- return None
-
-
-class BoundedAttributes(MutableMapping): # type: ignore
- """An ordered dict with a fixed max capacity.
+ @overload
+ def __init__(
+ self,
+ maxlen: int | None = None,
+ attributes: types.Attributes = None,
+ immutable: bool = True,
+ max_value_len: int | None = None,
+ ) -> None: ...
- Oldest elements are dropped when the dict is full and a new element is
- added.
- """
+ @overload
+ @deprecated(
+ "Creating BoundedAttributes with `extended_attributes` set is deprecated. "
+ "The `extended_attributes` param is no longer used and will be removed "
+ "in a future release. Extended attributes are now always used for attributes everywhere."
+ )
+ def __init__(
+ self,
+ maxlen: int | None = None,
+ attributes: types.Attributes = None,
+ immutable: bool = True,
+ max_value_len: int | None = None,
+ extended_attributes: bool = False,
+ ) -> None: ...
def __init__(
self,
maxlen: int | None = None,
- attributes: types._ExtendedAttributes | None = None,
+ attributes: types.Attributes = None,
immutable: bool = True,
max_value_len: int | None = None,
extended_attributes: bool = False,
- ):
- if maxlen is not None:
- if not isinstance(maxlen, int) or maxlen < 0:
- raise ValueError("maxlen must be valid int greater or equal to 0")
+ ) -> None:
+ if maxlen is not None and maxlen < 0:
+ raise ValueError("maxlen must be valid int greater or equal to 0")
+ self._dict: dict[str, types.AnyValue] = {}
self.maxlen = maxlen
self.dropped = 0
self.max_value_len = max_value_len
- self._extended_attributes = extended_attributes
- # OrderedDict is not used until the maxlen is reached for efficiency.
-
- self._dict: MutableMapping[str, types.AnyValue] | OrderedDict[str, types.AnyValue] = {}
self._lock = threading.Lock()
+ # setting False before adding items
+ self._immutable = False
if attributes:
- for key, value in attributes.items():
- self[key] = value
+ self._set_items(attributes)
self._immutable = immutable
def __repr__(self) -> str:
@@ -256,58 +163,56 @@ class BoundedAttributes(MutableMapping): # type: ignore
def __getitem__(self, key: str) -> types.AnyValue:
return self._dict[key]
+ def _raise_if_immutable(self) -> None:
+ if self._immutable:
+ raise TypeError("Cannot mutate immutable BoundedAttributes")
+
def __setitem__(self, key: str, value: types.AnyValue) -> None:
- if getattr(self, "_immutable", False): # type: ignore
- raise TypeError
+ self._raise_if_immutable()
if self.maxlen is not None and self.maxlen == 0:
with self._lock:
self.dropped += 1
- return
- if self._extended_attributes:
- value = _clean_extended_attribute(key, value, self.max_value_len)
- else:
- value = _clean_attribute(key, value, self.max_value_len) # type: ignore
- if value is None:
return
+ if not key or not isinstance(key, str):
+ _logger.warning(
+ "invalid key `%s`. must be non-empty string. Dropping key from attributes.",
+ key,
+ )
+ with self._lock:
+ self.dropped += 1
+ return
+ cleaned = _clean_attribute_value(value, self.max_value_len)
with self._lock:
- self._setitem_locked(key, value)
+ self._setitem_locked(key, cleaned)
- def _set_items(self, attributes: "types._ExtendedAttributes") -> None:
- if getattr(self, "_immutable", False): # type: ignore
- raise TypeError
+ def _set_items(self, attributes: Mapping[str, types.AnyValue]) -> None:
+ self._raise_if_immutable()
if self.maxlen is not None and self.maxlen == 0:
with self._lock:
self.dropped += len(attributes)
return
- cleaned = []
- for key, value in attributes.items():
- if self._extended_attributes:
- cv = _clean_extended_attribute(key, value, self.max_value_len)
- else:
- cv = _clean_attribute(key, value, self.max_value_len) # type: ignore
- if cv is None:
- continue
- cleaned.append((key, cv))
+ cleaned_attributes: Mapping[str, types.AnyValue] = _clean_attribute_value(attributes, self.max_value_len)
with self._lock:
- for key, cv in cleaned:
- self._setitem_locked(key, cv)
+ self.dropped += len(attributes) - len(cleaned_attributes)
+ for key, value in cleaned_attributes.items():
+ self._setitem_locked(key, value)
def _setitem_locked(self, key: str, value: types.AnyValue) -> None:
if key in self._dict:
del self._dict[key]
- elif self.maxlen is not None and len(self._dict) == self.maxlen:
- if not isinstance(self._dict, OrderedDict):
- self._dict = OrderedDict(self._dict)
- self._dict.popitem(last=False) # type: ignore
+ if self.maxlen is not None and len(self._dict) >= self.maxlen:
+ _logger.warning(
+ "Attributes dict is full. Dropping the oldest key-value pair from attributes to make space for the new key-value pair.",
+ )
+ # Dictionaries are insertion ordered in Python, this is the recommended way to get the oldest value.
+ del self._dict[next(iter(self._dict.keys()))]
self.dropped += 1
- self._dict[key] = value # type: ignore
+ self._dict[key] = value
def __delitem__(self, key: str) -> None:
- if getattr(self, "_immutable", False): # type: ignore
- raise TypeError
- with self._lock:
- del self._dict[key]
+ self._raise_if_immutable()
+ del self._dict[key]
def __iter__(self):
if self._immutable:
@@ -318,12 +223,11 @@ class BoundedAttributes(MutableMapping): # type: ignore
def __len__(self) -> int:
return len(self._dict)
- def __deepcopy__(self, memo: dict) -> "BoundedAttributes":
+ def __deepcopy__(self, memo: dict[int, Any]) -> "BoundedAttributes":
copy_ = BoundedAttributes(
maxlen=self.maxlen,
immutable=self._immutable,
max_value_len=self.max_value_len,
- extended_attributes=self._extended_attributes,
)
memo[id(self)] = copy_
with self._lock:
@@ -333,5 +237,5 @@ class BoundedAttributes(MutableMapping): # type: ignore
copy_.dropped = self.dropped
return copy_
- def copy(self): # type: ignore
- return self._dict.copy() # type: ignore
+ def copy(self) -> MutableMapping[str, types.AnyValue]:
+ return self._dict.copy()
diff --git a/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py b/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py
index ed1bb750..183966b1 100644
--- a/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py
@@ -96,7 +96,7 @@ class MeterProvider(ABC):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
) -> "Meter":
"""Returns a `Meter` for use by the given instrumentation library.
@@ -135,7 +135,7 @@ class NoOpMeterProvider(MeterProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
) -> "Meter":
"""Returns a NoOpMeter."""
return NoOpMeter(name, version=version, schema_url=schema_url)
@@ -152,7 +152,7 @@ class _ProxyMeterProvider(MeterProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
) -> "Meter":
with self._lock:
if self._real_meter_provider is not None:
@@ -839,7 +839,7 @@ def get_meter(
version: str = "",
meter_provider: MeterProvider | None = None,
schema_url: str | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
) -> "Meter":
"""Returns a `Meter` for use by the given instrumentation library.
diff --git a/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py b/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py
index 7e27e520..bccdbc30 100644
--- a/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py
+++ b/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py
@@ -158,7 +158,7 @@ class Counter(Synchronous):
def add(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
"""Records an increment to the counter.
@@ -185,7 +185,7 @@ class NoOpCounter(Counter):
def add(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
return super().add(amount, attributes=attributes, context=context)
@@ -195,7 +195,7 @@ class _ProxyCounter(_ProxyInstrument[Counter], Counter):
def add(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
if self._real_instrument:
@@ -216,7 +216,7 @@ class UpDownCounter(Synchronous):
def add(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
"""Records an increment or decrement to the counter.
@@ -247,7 +247,7 @@ class NoOpUpDownCounter(UpDownCounter):
def add(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
return super().add(amount, attributes=attributes, context=context)
@@ -257,7 +257,7 @@ class _ProxyUpDownCounter(_ProxyInstrument[UpDownCounter], UpDownCounter):
def add(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
if self._real_instrument:
@@ -363,7 +363,7 @@ class Histogram(Synchronous):
def record(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
"""Records a measurement.
@@ -402,7 +402,7 @@ class NoOpHistogram(Histogram):
def record(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
return super().record(amount, attributes=attributes, context=context)
@@ -422,7 +422,7 @@ class _ProxyHistogram(_ProxyInstrument[Histogram], Histogram):
def record(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
if self._real_instrument:
@@ -482,7 +482,7 @@ class Gauge(Synchronous):
def set(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
"""Records the current value of the gauge.
@@ -513,7 +513,7 @@ class NoOpGauge(Gauge):
def set(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
return super().set(amount, attributes=attributes, context=context)
@@ -526,7 +526,7 @@ class _ProxyGauge(
def set(
self,
amount: int | float,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
) -> None:
if self._real_instrument:
diff --git a/opentelemetry-api/src/opentelemetry/trace/__init__.py b/opentelemetry-api/src/opentelemetry/trace/__init__.py
index 47aaac84..b705b404 100644
--- a/opentelemetry-api/src/opentelemetry/trace/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/trace/__init__.py
@@ -184,7 +184,7 @@ class TracerProvider(ABC):
instrumenting_module_name: str,
instrumenting_library_version: str | None = None,
schema_url: str | None = None,
- attributes: types.Attributes | None = None,
+ attributes: types.Attributes = None,
) -> "Tracer":
"""Returns a `Tracer` for use by the given instrumentation library.
@@ -227,7 +227,7 @@ class NoOpTracerProvider(TracerProvider):
instrumenting_module_name: str,
instrumenting_library_version: str | None = None,
schema_url: str | None = None,
- attributes: types.Attributes | None = None,
+ attributes: types.Attributes = None,
) -> "Tracer":
# pylint:disable=no-self-use,unused-argument
return NoOpTracer()
@@ -247,7 +247,7 @@ class ProxyTracerProvider(TracerProvider):
instrumenting_module_name: str,
instrumenting_library_version: str | None = None,
schema_url: str | None = None,
- attributes: types.Attributes | None = None,
+ attributes: types.Attributes = None,
) -> "Tracer":
if _TRACER_PROVIDER:
return _TRACER_PROVIDER.get_tracer(
@@ -408,7 +408,7 @@ class ProxyTracer(Tracer):
instrumenting_module_name: str,
instrumenting_library_version: str | None = None,
schema_url: str | None = None,
- attributes: types.Attributes | None = None,
+ attributes: types.Attributes = None,
):
self._instrumenting_module_name = instrumenting_module_name
self._instrumenting_library_version = instrumenting_library_version
@@ -522,7 +522,7 @@ def get_tracer(
instrumenting_library_version: str | None = None,
tracer_provider: TracerProvider | None = None,
schema_url: str | None = None,
- attributes: types.Attributes | None = None,
+ attributes: types.Attributes = None,
) -> "Tracer":
"""Returns a `Tracer` for use by the given instrumentation library.
diff --git a/opentelemetry-api/src/opentelemetry/trace/span.py b/opentelemetry-api/src/opentelemetry/trace/span.py
index 745f4f5f..a68489c8 100644
--- a/opentelemetry-api/src/opentelemetry/trace/span.py
+++ b/opentelemetry-api/src/opentelemetry/trace/span.py
@@ -82,7 +82,7 @@ class Span(abc.ABC):
"""
@abc.abstractmethod
- def set_attributes(self, attributes: Mapping[str, types.AttributeValue]) -> None:
+ def set_attributes(self, attributes: Mapping[str, types.AnyValue]) -> None:
"""Sets Attributes.
Sets Attributes with the key and value passed as arguments dict.
@@ -94,7 +94,7 @@ class Span(abc.ABC):
"""
@abc.abstractmethod
- def set_attribute(self, key: str, value: types.AttributeValue) -> None:
+ def set_attribute(self, key: str, value: types.AnyValue) -> None:
"""Sets an Attribute.
Sets a single Attribute with the key and value passed as arguments.
@@ -523,10 +523,10 @@ class NonRecordingSpan(Span):
def end(self, end_time: int | None = None) -> None:
pass
- def set_attributes(self, attributes: Mapping[str, types.AttributeValue]) -> None:
+ def set_attributes(self, attributes: Mapping[str, types.AnyValue]) -> None:
pass
- def set_attribute(self, key: str, value: types.AttributeValue) -> None:
+ def set_attribute(self, key: str, value: types.AnyValue) -> None:
pass
def add_event(
diff --git a/opentelemetry-api/src/opentelemetry/util/types.py b/opentelemetry-api/src/opentelemetry/util/types.py
index 1e8e74a3..4456a47f 100644
--- a/opentelemetry-api/src/opentelemetry/util/types.py
+++ b/opentelemetry-api/src/opentelemetry/util/types.py
@@ -6,10 +6,10 @@ from collections.abc import Mapping, Sequence
# This is the implementation of the "Any" type as specified by the specifications of OpenTelemetry data model for logs.
# For more details, refer to the OTel specification:
# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#type-any
-AnyValue = str | bool | int | float | bytes | Sequence["AnyValue"] | Mapping[str, "AnyValue"] | None
+AnyValue = AttributeValue = str | bool | int | float | bytes | Sequence["AnyValue"] | Mapping[str, "AnyValue"] | None
+Attributes = Mapping[str, AnyValue] | None
-AttributeValue = str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]
-Attributes = Mapping[str, AttributeValue] | None
+# Deprecated type, do not use.
AttributesAsKey = tuple[
tuple[
str,
@@ -24,5 +24,3 @@ AttributesAsKey = tuple[
],
...,
]
-
-_ExtendedAttributes = Mapping[str, "AnyValue"]
diff --git a/opentelemetry-api/tests/attributes/test_attributes.py b/opentelemetry-api/tests/attributes/test_attributes.py
index eb210b27..29e98264 100644
--- a/opentelemetry-api/tests/attributes/test_attributes.py
+++ b/opentelemetry-api/tests/attributes/test_attributes.py
@@ -8,167 +8,16 @@ import logging
import threading
import unittest
import unittest.mock
-from collections.abc import MutableSequence
from opentelemetry.attributes import (
BoundedAttributes,
- _clean_attribute,
- _clean_extended_attribute,
- _clean_extended_attribute_value,
+ _clean_attribute_value,
)
-class TestAttributes(unittest.TestCase):
- # pylint: disable=invalid-name
- def assertValid(self, value, key="k"):
- expected = value
- if isinstance(value, MutableSequence):
- expected = tuple(value)
- self.assertEqual(_clean_attribute(key, value, None), expected)
-
- def assertInvalid(self, value, key="k"):
- self.assertIsNone(_clean_attribute(key, value, None))
-
- def test_attribute_key_validation(self):
- # only non-empty strings are valid keys
- self.assertInvalid(1, "")
- self.assertInvalid(1, 1)
- self.assertInvalid(1, {})
- self.assertInvalid(1, [])
- self.assertInvalid(1, b"1")
- self.assertValid(1, "k")
- self.assertValid(1, "1")
-
- def test_clean_attribute(self):
- self.assertInvalid([1, 2, 3.4, "ss", 4])
- self.assertInvalid([{}, 1, 2, 3.4, 4])
- self.assertInvalid(["sw", "lf", 3.4, "ss"])
- self.assertInvalid([1, 2, 3.4, 5])
- self.assertInvalid({})
- self.assertInvalid([1, True])
- self.assertValid(True)
- self.assertValid("hi")
- self.assertValid(3.4)
- self.assertValid(15)
- self.assertValid([1, 2, 3, 5])
- self.assertValid([1.2, 2.3, 3.4, 4.5])
- self.assertValid([True, False])
- self.assertValid(["ss", "dw", "fw"])
- self.assertValid([])
- # None in sequences are valid
- self.assertValid(["A", None, None])
- self.assertValid(["A", None, None, "B"])
- self.assertValid([None, None])
- self.assertInvalid(["A", None, 1])
- self.assertInvalid([None, "A", None, 1])
-
- # test keys
- self.assertValid("value", "key")
- self.assertInvalid("value", "")
- self.assertInvalid("value", None)
-
- def test_sequence_attr_decode(self):
- seq = [
- None,
- b"Content-Disposition",
- b"Content-Type",
- b"\x81",
- b"Keep-Alive",
- ]
- expected = [
- None,
- "Content-Disposition",
- "Content-Type",
- None,
- "Keep-Alive",
- ]
- self.assertEqual(_clean_attribute("headers", seq, None), tuple(expected))
-
-
-class TestExtendedAttributes(unittest.TestCase):
- # pylint: disable=invalid-name
- def assertValid(self, value, key="k"):
- expected = value
- if isinstance(value, MutableSequence):
- expected = tuple(value)
- self.assertEqual(_clean_extended_attribute(key, value, None), expected)
-
- def assertInvalid(self, value, key="k"):
- self.assertIsNone(_clean_extended_attribute(key, value, None))
-
- def test_attribute_key_validation(self):
- # only non-empty strings are valid keys
- self.assertInvalid(1, "")
- self.assertInvalid(1, 1)
- self.assertInvalid(1, {})
- self.assertInvalid(1, [])
- self.assertInvalid(1, b"1")
- self.assertValid(1, "k")
- self.assertValid(1, "1")
-
- def test_clean_extended_attribute(self):
- self.assertInvalid([1, 2, 3.4, "ss", 4])
- self.assertInvalid([{}, 1, 2, 3.4, 4])
- self.assertInvalid(["sw", "lf", 3.4, "ss"])
- self.assertInvalid([1, 2, 3.4, 5])
- self.assertInvalid([1, True])
- self.assertValid(None)
- self.assertValid(True)
- self.assertValid("hi")
- self.assertValid(3.4)
- self.assertValid(15)
- self.assertValid([1, 2, 3, 5])
- self.assertValid([1.2, 2.3, 3.4, 4.5])
- self.assertValid([True, False])
- self.assertValid(["ss", "dw", "fw"])
- self.assertValid([])
- # None in sequences are valid
- self.assertValid(["A", None, None])
- self.assertValid(["A", None, None, "B"])
- self.assertValid([None, None])
- self.assertInvalid(["A", None, 1])
- self.assertInvalid([None, "A", None, 1])
- # mappings
- self.assertValid({})
- self.assertValid({"k": "v"})
- # mappings in sequences
- self.assertValid([{"k": "v"}])
-
- # test keys
- self.assertValid("value", "key")
- self.assertInvalid("value", "")
- self.assertInvalid("value", None)
-
- def test_sequence_attr_decode(self):
- seq = [
- None,
- b"Content-Disposition",
- b"Content-Type",
- b"\x81",
- b"Keep-Alive",
- ]
- self.assertEqual(_clean_extended_attribute("headers", seq, None), tuple(seq))
-
- def test_mapping(self):
- mapping = {
- "": "invalid",
- b"bytes": "invalid",
- "none": {"": "invalid"},
- "valid_primitive": "str",
- "valid_sequence": ["str"],
- "invalid_sequence": ["str", 1],
- "valid_mapping": {"str": 1},
- "invalid_mapping": {"": 1},
- }
- expected = {
- "none": {},
- "valid_primitive": "str",
- "valid_sequence": ("str",),
- "invalid_sequence": None,
- "valid_mapping": {"str": 1},
- "invalid_mapping": {},
- }
- self.assertEqual(_clean_extended_attribute("headers", mapping, None), expected)
+class _NoStrNoReprObject:
+ def __init__(self):
+ pass
class TestBoundedAttributes(unittest.TestCase):
@@ -180,11 +29,94 @@ class TestBoundedAttributes(unittest.TestCase):
"vaccinated": True,
}
- def test_negative_maxlen(self):
+ def test_clean_attribute_value_with_various_params(self):
+ # A python object that isn't a primitive and has no string/repr method is converted to None.
+ with self.assertLogs("opentelemetry", level="WARNING") as cm:
+ self.assertEqual(
+ _clean_attribute_value(_NoStrNoReprObject(), None),
+ None,
+ )
+ self.assertEqual(len(cm.output), 1)
+ self.assertIn("Expected one of bool, str, None, bytes, int, float", cm.output[0])
+
+ valid_primitive_sequence = [1, 2.2, None, "cookie"]
+ self.assertEqual(
+ _clean_attribute_value(valid_primitive_sequence, None),
+ tuple(valid_primitive_sequence),
+ )
+ for valid_primitive in valid_primitive_sequence:
+ self.assertEqual(_clean_attribute_value(valid_primitive, None), valid_primitive)
+
+ self.assertEqual(_clean_attribute_value(b"hello", 4), b"hello")
+
+ with self.assertLogs("opentelemetry", level="WARNING") as cm:
+ # String is truncated.
+ self.assertEqual(_clean_attribute_value("a" * 1000, 5), "aaaaa")
+ self.assertEqual(len(cm.output), 1)
+ self.assertIn("String attribute value exceeds max length", cm.output[0])
+
+ # Sequence of different types of values. List converted to tuple.
+ self.assertEqual(
+ _clean_attribute_value(["a", 2, _NoStrNoReprObject(), None, b"\xff"], None),
+ ("a", 2, None, None, b"\xff"),
+ )
+
+ # non-str key in map... will be converted to string
+ with self.assertLogs("opentelemetry", level="WARNING") as cm:
+ self.assertEqual(_clean_attribute_value({2.2: 4.4}, None), {"2.2": 4.4})
+ self.assertEqual(len(cm.output), 1)
+ self.assertIn(
+ "Invalid type",
+ cm.output[0],
+ )
+
+ # Mapping of values..
+ # Non string key without a string conversion method is dropped.
+ self.assertEqual(
+ _clean_attribute_value(
+ {
+ "a": 1,
+ _NoStrNoReprObject(): 2,
+ "c": 3,
+ "d": [2, 3],
+ "bytes": b"\xff",
+ },
+ None,
+ ),
+ {"a": 1, "c": 3, "d": (2, 3), "bytes": b"\xff"},
+ )
+
+ def test_same_key_value_overwritten(self):
+ bdict = BoundedAttributes(1, {"name": "Firulais"}, immutable=False)
+ self.assertEqual(bdict["name"], "Firulais")
+ self.assertEqual(bdict.dropped, 0)
+ bdict["name"] = "Bruno"
+ self.assertEqual(bdict["name"], "Bruno")
+ self.assertEqual(bdict.dropped, 0)
+
+ def test_invalid_key_not_used(self):
+ bdict = BoundedAttributes(50, {}, immutable=False)
+ with self.assertLogs("opentelemetry", level="WARNING") as cm:
+ bdict[1] = 2
+ self.assertEqual(len(cm.output), 1)
+ self.assertIn("invalid key", cm.output[0])
+ self.assertNotIn(1, bdict)
+ self.assertEqual(bdict.dropped, 1)
+
+ def test_maxlen_reached(self):
+ bdict = BoundedAttributes(1, {"first": "value"}, immutable=False)
+ with self.assertLogs("opentelemetry", level="WARNING") as cm:
+ bdict["second"] = "another"
+ self.assertIn("Attributes dict is full. Dropping the oldest", cm.output[0])
+ self.assertNotIn("first", bdict)
+ self.assertEqual(bdict["second"], "another")
+ self.assertEqual(bdict.dropped, 1)
+
+ def test_negative_maxlen_not_allowed(self):
with self.assertRaises(ValueError):
BoundedAttributes(-1)
- def test_from_map(self):
+ def test_base_copy_isolated_and_len_works(self):
dic_len = len(self.base)
base_copy = self.base.copy()
bdict = BoundedAttributes(dic_len, base_copy)
@@ -201,13 +133,7 @@ class TestBoundedAttributes(unittest.TestCase):
# test that iter yields the correct number of elements
self.assertEqual(len(tuple(bdict)), dic_len)
- # map too big
- half_len = dic_len // 2
- bdict = BoundedAttributes(half_len, self.base)
- self.assertEqual(len(tuple(bdict)), half_len)
- self.assertEqual(bdict.dropped, dic_len - half_len)
-
- def test_bounded_dict(self):
+ def test_basic_insertion_update_iteration_and_deletion(self):
# create empty dict
dic_len = len(self.base)
bdict = BoundedAttributes(dic_len, immutable=False)
@@ -231,15 +157,12 @@ class TestBoundedAttributes(unittest.TestCase):
bdict["name"] = "Bruno"
self.assertEqual(bdict.dropped, 0)
- # try to append more elements
+ # try to append more elements, old elements should be dropped
for key in self.base:
bdict["new-" + key] = self.base[key]
self.assertEqual(len(bdict), dic_len)
self.assertEqual(bdict.dropped, dic_len)
- # Invalid values shouldn't be considered for `dropped`
- bdict["invalid-seq"] = [None, 1, "2"]
- self.assertEqual(bdict.dropped, dic_len)
# test that elements in the dict are the new ones
for key in self.base:
@@ -252,14 +175,6 @@ class TestBoundedAttributes(unittest.TestCase):
with self.assertRaises(KeyError):
_ = bdict["new-name"]
- def test_no_limit_code(self):
- bdict = BoundedAttributes(maxlen=None, immutable=False)
- for num in range(100):
- bdict[str(num)] = num
-
- for num in range(100):
- self.assertEqual(bdict[str(num)], num)
-
def test_immutable(self):
bdict = BoundedAttributes()
with self.assertRaises(TypeError):
@@ -275,7 +190,7 @@ class TestBoundedAttributes(unittest.TestCase):
With _clean_attribute called before the lock is acquired, no deadlock
occurs.
"""
- bdict = BoundedAttributes(immutable=False)
+ bdict = BoundedAttributes(immutable=False, max_value_len=20)
class ReentrantHandler(logging.Handler):
def emit(self, _record):
@@ -290,9 +205,8 @@ class TestBoundedAttributes(unittest.TestCase):
completed = threading.Event()
def run():
- # None is an invalid attribute value and triggers _logger.warning
- # in _clean_attribute, which fires the ReentrantHandler above.
- bdict["trigger.key"] = None
+ # A string value > 20 triggers a warning log in _clean_attribute, which fires the ReentrantHandler above.
+ bdict["trigger.key"] = "a" * 21
completed.set()
thread = threading.Thread(target=run, daemon=True)
@@ -307,39 +221,17 @@ class TestBoundedAttributes(unittest.TestCase):
finally:
otel_logger.removeHandler(handler)
- # pylint: disable=no-self-use
- def test_extended_attributes(self):
- bdict = BoundedAttributes(extended_attributes=True, immutable=False)
- with unittest.mock.patch(
- "opentelemetry.attributes._clean_extended_attribute",
- return_value="mock_value",
- ) as clean_extended_attribute_mock:
- bdict["key"] = "value"
-
- clean_extended_attribute_mock.assert_called_once()
-
def test_wsgi_request_conversion_to_string(self):
- """Test that WSGI request objects are converted to strings when _clean_extended_attribute is called."""
+ """Test that WSGI request objects are converted to strings when _clean_attribute_value is called."""
class DummyWSGIRequest:
def __str__(self):
return "<DummyWSGIRequest method=GET path=/example/>"
- wsgi_request = DummyWSGIRequest()
-
- cleaned_value = _clean_extended_attribute("request", wsgi_request, None)
-
- # Verify we get a string back from the cleaner
- self.assertIsInstance(cleaned_value, str)
- self.assertEqual("<DummyWSGIRequest method=GET path=/example/>", cleaned_value)
-
- def test_invalid_anyvalue_type_raises_typeerror(self):
- class BadStr:
- def __str__(self):
- raise RuntimeError("boom")
-
- with self.assertRaises(TypeError):
- _clean_extended_attribute_value(BadStr(), None)
+ self.assertEqual(
+ "<DummyWSGIRequest method=GET path=/example/>",
+ _clean_attribute_value(DummyWSGIRequest(), None),
+ )
def test_deepcopy(self):
bdict = BoundedAttributes(4, self.base, immutable=False)
diff --git a/opentelemetry-api/tests/logs/test_proxy.py b/opentelemetry-api/tests/logs/test_proxy.py
index c3c3519d..876d659c 100644
--- a/opentelemetry-api/tests/logs/test_proxy.py
+++ b/opentelemetry-api/tests/logs/test_proxy.py
@@ -8,7 +8,7 @@ from unittest.mock import Mock
import opentelemetry._logs._internal as _logs_internal
from opentelemetry import _logs
from opentelemetry.test.globals_test import LoggingGlobalsTest
-from opentelemetry.util.types import _ExtendedAttributes
+from opentelemetry.util.types import Attributes
class TestProvider(_logs.NoOpLoggerProvider):
@@ -17,7 +17,7 @@ class TestProvider(_logs.NoOpLoggerProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> _logs.Logger:
return LoggerTest(name)
diff --git a/opentelemetry-api/tests/trace/test_proxy.py b/opentelemetry-api/tests/trace/test_proxy.py
index 13f380c7..8d4ee165 100644
--- a/opentelemetry-api/tests/trace/test_proxy.py
+++ b/opentelemetry-api/tests/trace/test_proxy.py
@@ -21,7 +21,7 @@ class TestProvider(trace.NoOpTracerProvider):
instrumenting_module_name: str,
instrumenting_library_version: str | None = None,
schema_url: str | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
) -> trace.Tracer:
return TestTracer()
diff --git a/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py b/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py
index a150a261..0cd804dc 100644
--- a/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py
+++ b/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py
@@ -29,7 +29,7 @@ from opentelemetry.sdk.resources import (
ServiceInstanceIdResourceDetector,
_HostResourceDetector,
)
-from opentelemetry.util.types import AttributeValue
+from opentelemetry.util.types import AnyValue
_logger = logging.getLogger(__name__)
@@ -147,15 +147,15 @@ def create_resource(config: ResourceConfig | None) -> Resource:
return result.merge(config_resource)
-def _detect_service(_config: Any) -> dict[str, AttributeValue]:
+def _detect_service(_config: Any) -> dict[str, AnyValue]:
"""Service detector: generates instance ID and reads OTEL_SERVICE_NAME."""
- attrs: dict[str, AttributeValue] = dict(ServiceInstanceIdResourceDetector().detect().attributes)
+ attrs: dict[str, AnyValue] = dict(ServiceInstanceIdResourceDetector().detect().attributes)
if service_name := os.environ.get(OTEL_SERVICE_NAME):
attrs[SERVICE_NAME] = service_name
return attrs
-_RESOURCE_DETECTOR_REGISTRY: dict[str, Callable[[Any], dict[str, AttributeValue]]] = {
+_RESOURCE_DETECTOR_REGISTRY: dict[str, Callable[[Any], dict[str, AnyValue]]] = {
"service": _detect_service,
"host": lambda _: dict(_HostResourceDetector().detect().attributes),
"process": lambda _: dict(ProcessResourceDetector().detect().attributes),
diff --git a/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py b/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py
index 440a37fc..746e62eb 100644
--- a/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py
+++ b/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# pylint: disable=invalid-name
+import json
import random
import pytest
@@ -81,37 +82,80 @@ def test_histogram_record_10(benchmark, num_labels):
benchmark(benchmark_histogram_record_10)
+@pytest.mark.parametrize("num_labels", [1, 3])
+def test_histogram_record_10_small_mapping_attrs(benchmark, num_labels):
+ def test_histogram_record_10_attrs():
+ hist10.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={f"Key{i}": {"k1": "v1"} for i in range(num_labels)},
+ )
+
+ benchmark(test_histogram_record_10_attrs)
+
+
+@pytest.mark.parametrize("num_labels", [1, 3])
+def test_histogram_record_10_complex_attrs(benchmark, num_labels):
+ def test_histogram_record_10_attrs():
+ hist10.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={f"Key{i}": {"k1": "v1", "k2": {"k3": "v3", "k4": [1, 2, 3]}} for i in range(num_labels)},
+ )
+
+ benchmark(test_histogram_record_10_attrs)
+
+
+@pytest.mark.parametrize("num_labels", [1, 3])
+def test_histogram_record_10_array_attrs(benchmark, num_labels):
+ def test_histogram_record_10_attrs():
+ hist10.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={f"Key{i}": ["k1", "v1", "k2", "k3", "v3", "k4", "1", "2", "3"] for i in range(num_labels)},
+ )
+
+ benchmark(test_histogram_record_10_attrs)
+
+
+@pytest.mark.parametrize("num_labels", [1, 3])
+def test_histogram_record_10_json_string_attrs(benchmark, num_labels):
+ def test_histogram_record_10_attrs():
+ hist10.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={
+ f"Key{i}": json.dumps({"k1": "v1", "k2": {"k3": "v3", "k4": [1, 2, 3]}}) for i in range(num_labels)
+ },
+ )
+
+ benchmark(test_histogram_record_10_attrs)
+
+
@pytest.mark.parametrize("num_labels", [0, 1, 3, 5, 7])
def test_histogram_record_49(benchmark, num_labels):
- labels = {}
- for i in range(num_labels):
- labels[f"Key{i}"] = "Value{i}"
-
def benchmark_histogram_record_49():
- hist49.record(random.random() * MAX_BOUND_VALUE)
+ hist49.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={f"Key{i}": f"Value{i}" for i in range(num_labels)},
+ )
benchmark(benchmark_histogram_record_49)
@pytest.mark.parametrize("num_labels", [0, 1, 3, 5, 7])
def test_histogram_record_50(benchmark, num_labels):
- labels = {}
- for i in range(num_labels):
- labels[f"Key{i}"] = "Value{i}"
-
def benchmark_histogram_record_50():
- hist50.record(random.random() * MAX_BOUND_VALUE)
+ hist50.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={f"Key{i}": f"Value{i}" for i in range(num_labels)},
+ )
benchmark(benchmark_histogram_record_50)
@pytest.mark.parametrize("num_labels", [0, 1, 3, 5, 7])
def test_histogram_record_1000(benchmark, num_labels):
- labels = {}
- for i in range(num_labels):
- labels[f"Key{i}"] = "Value{i}"
-
def benchmark_histogram_record_1000():
- hist1000.record(random.random() * MAX_BOUND_VALUE)
+ hist1000.record(
+ random.random() * MAX_BOUND_VALUE,
+ attributes={f"Key{i}": f"Value{i}" for i in range(num_labels)},
+ )
benchmark(benchmark_histogram_record_1000)
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py
index 471a94da..300f5c3c 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py
@@ -12,13 +12,16 @@ import os
import threading
import traceback
import warnings
-from collections.abc import Callable
+from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
from os import environ
from threading import Lock
from time import time_ns
+from types import NoneType
from typing import ( # noqa
Any,
+ Tuple,
+ Union,
cast,
overload,
)
@@ -35,7 +38,7 @@ from opentelemetry._logs import (
get_logger,
get_logger_provider,
)
-from opentelemetry.attributes import _VALID_ANY_VALUE_TYPES, BoundedAttributes
+from opentelemetry.attributes import BoundedAttributes
from opentelemetry.context import get_current
from opentelemetry.context.context import Context
from opentelemetry.metrics import MeterProvider, get_meter_provider
@@ -76,7 +79,7 @@ from opentelemetry.trace import (
format_span_id,
format_trace_id,
)
-from opentelemetry.util.types import AnyValue, _ExtendedAttributes
+from opentelemetry.util.types import AnyValue, Attributes
# pylint: disable=too-many-lines
@@ -556,7 +559,7 @@ class LoggingHandler(logging.Handler):
)
@staticmethod
- def _get_attributes(record: logging.LogRecord) -> _ExtendedAttributes:
+ def _get_attributes(record: logging.LogRecord) -> Attributes:
attributes = {k: v for k, v in vars(record).items() if k not in _RESERVED_ATTRS}
# Add standard code attributes for logs.
@@ -598,7 +601,21 @@ class LoggingHandler(logging.Handler):
# For more background, see: https://github.com/open-telemetry/opentelemetry-python/pull/4216
if not record.args and not isinstance(record.msg, str):
# if record.msg is not a value we can export, cast it to string
- if not isinstance(record.msg, _VALID_ANY_VALUE_TYPES):
+ # TODO: https://github.com/open-telemetry/opentelemetry-python/issues/5304 - do something better
+ # than just casting to a string.
+ if not isinstance(
+ record.msg,
+ (
+ NoneType,
+ bool,
+ bytes,
+ int,
+ float,
+ str,
+ Sequence,
+ Mapping,
+ ),
+ ):
body = str(record.msg)
else:
body = record.msg
@@ -707,7 +724,7 @@ class Logger(APILogger):
severity_number: SeverityNumber | None = None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> None:
@@ -831,7 +848,7 @@ class LoggerProvider(APILoggerProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> Logger:
scope = InstrumentationScope(name, version, schema_url, attributes)
@@ -862,7 +879,7 @@ class LoggerProvider(APILoggerProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> APILogger:
if self._disabled:
return NoOpLogger(
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py
index 4dd4c7ee..bd4a9538 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py
@@ -7,7 +7,7 @@ import traceback
from opentelemetry._logs import LogRecord
from opentelemetry.attributes import BoundedAttributes
from opentelemetry.semconv.attributes import exception_attributes
-from opentelemetry.util.types import AnyValue, _ExtendedAttributes
+from opentelemetry.util.types import AnyValue, Attributes
def _get_exception_attributes(
@@ -25,15 +25,15 @@ def _get_exception_attributes(
def _get_attributes_with_exception(
- attributes: _ExtendedAttributes | None,
+ attributes: Attributes,
exception: BaseException | None,
-) -> _ExtendedAttributes | None:
+) -> Attributes:
if exception is None:
return attributes
exception_attributes_map = _get_exception_attributes(exception)
if attributes is None:
- attributes_map: _ExtendedAttributes = {}
+ attributes_map: Attributes = {}
else:
attributes_map = attributes
@@ -44,7 +44,6 @@ def _get_attributes_with_exception(
attributes=bounded_attributes,
immutable=False,
max_value_len=bounded_attributes.max_value_len,
- extended_attributes=bounded_attributes._extended_attributes, # pylint: disable=protected-access
)
merged.dropped = bounded_attributes.dropped
for key, value in exception_attributes_map.items():
@@ -57,7 +56,7 @@ def _get_attributes_with_exception(
def _copy_log_record(
record: LogRecord,
- attributes: _ExtendedAttributes | None,
+ attributes: Attributes,
) -> LogRecord:
copied_record = LogRecord(
timestamp=record.timestamp,
@@ -98,7 +97,7 @@ def _create_log_record_with_exception(
severity_number=None,
severity_text: str | None = None,
body: AnyValue | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
event_name: str | None = None,
exception: BaseException | None = None,
) -> LogRecord:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py
index 6f68ad96..303f6292 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py
@@ -162,7 +162,7 @@ OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT = "OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"
"""
.. envvar:: OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT
-The :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed attribute length.
+The :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed attribute value length for string attribute values.
"""
OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT = "OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT"
@@ -193,8 +193,7 @@ OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = "OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT
"""
.. envvar:: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT
-The :envvar:`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed length
-span attribute values can have. This takes precedence over :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`.
+The :envvar:`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed attribute value length for string span attribute values. This takes precedence over :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`.
"""
OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT = "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT"
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py
index 016885bb..8072b6b2 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py
@@ -606,7 +606,7 @@ class MeterProvider(APIMeterProvider):
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
) -> APIMeter:
if self._disabled:
return NoOpMeter(name, version=version, schema_url=schema_url)
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py
index 8abd9d51..43240429 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py
@@ -1,12 +1,14 @@
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0
-
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from logging import getLogger
from threading import Lock
from time import time_ns
-from typing import cast
+from types import NoneType
+from typing import TYPE_CHECKING, cast
+
+from typing_extensions import assert_never
from opentelemetry.sdk.metrics._internal.aggregation import (
Aggregation,
@@ -19,9 +21,32 @@ from opentelemetry.sdk.metrics._internal.instrument import _Instrument
from opentelemetry.sdk.metrics._internal.measurement import Measurement
from opentelemetry.sdk.metrics._internal.point import DataPointT
from opentelemetry.sdk.metrics._internal.view import View
+from opentelemetry.util.types import AnyValue, Attributes
_logger = getLogger(__name__)
+_HashedAttributes = str | bool | int | float | bytes | None | tuple["_HashedAttributes", ...]
+
+
+# pylint: disable=inconsistent-return-statements
+def _hash_attributes(value: Attributes | AnyValue) -> _HashedAttributes:
+ # Attributes have been cleaned and validated when Measurement was instantiated,
+ # so value is guaranteed to match one of the branches below at runtime.
+ if isinstance(value, (NoneType, str, int, float, bool, bytes)):
+ return value
+ if isinstance(value, Sequence):
+ return tuple(_hash_attributes(v) for v in value)
+ if isinstance(value, Mapping):
+ return tuple(
+ (k, _hash_attributes(value[k]))
+ for k in sorted(
+ value,
+ key=lambda item: item if isinstance(item, str) else str(item),
+ )
+ )
+ if TYPE_CHECKING:
+ assert_never(value)
+
class _ViewInstrumentMatch:
def __init__(
@@ -32,7 +57,7 @@ class _ViewInstrumentMatch:
):
self._view = view
self._instrument = instrument
- self._attributes_aggregation: dict[frozenset, _Aggregation] = {}
+ self._attributes_aggregation: dict[_HashedAttributes, _Aggregation] = {}
self._lock = Lock()
self._instrument_class_aggregation = instrument_class_aggregation
self._name = self._view._name or self._instrument.name
@@ -80,18 +105,16 @@ class _ViewInstrumentMatch:
# pylint: disable=protected-access
def consume_measurement(self, measurement: Measurement, should_sample_exemplar: bool = True) -> None:
- if self._view._attribute_keys is not None:
- attributes = {}
-
- for key, value in (measurement.attributes or {}).items():
- if key in self._view._attribute_keys:
- attributes[key] = value
- elif measurement.attributes is not None:
+ attributes = {}
+ if measurement.attributes:
+ # Make a shallow copy since the user can mutate the dict after the fact.
+ # The user can still modify mutable attribute values (lists/dicts)
+ # leading to unexpected behavior, but deep copying is expensive.
attributes = dict(measurement.attributes)
- else:
- attributes = {}
+ if self._view._attribute_keys is not None:
+ attributes = {k: v for k, v in attributes.items() if k in self._view._attribute_keys}
- aggr_key = frozenset(attributes.items())
+ aggr_key = _hash_attributes(attributes)
if aggr_key not in self._attributes_aggregation:
with self._lock:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py
index c3ee9c47..d941569b 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py
@@ -32,6 +32,7 @@ from opentelemetry.metrics._internal.instrument import (
_MetricsHistogramAdvisory,
)
from opentelemetry.sdk.metrics._internal.measurement import Measurement
+from opentelemetry.util.types import Attributes
if TYPE_CHECKING:
from opentelemetry.sdk.metrics._internal import (
@@ -188,7 +189,7 @@ class Counter(_Synchronous, APICounter):
def add(
self,
amount: int | float,
- attributes: dict[str, str] | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
):
if not self._is_enabled():
@@ -226,7 +227,7 @@ class UpDownCounter(_Synchronous, APIUpDownCounter):
def add(
self,
amount: int | float,
- attributes: dict[str, str] | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
):
if not self._is_enabled():
@@ -296,7 +297,7 @@ class Histogram(_Synchronous, APIHistogram):
def record(
self,
amount: int | float,
- attributes: dict[str, str] | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
):
if not self._is_enabled():
@@ -337,7 +338,7 @@ class Gauge(_Synchronous, APIGauge):
def set(
self,
amount: int | float,
- attributes: dict[str, str] | None = None,
+ attributes: Attributes = None,
context: Context | None = None,
):
if not self._is_enabled():
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py
index cd81c39f..4e9d5eea 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py
@@ -3,12 +3,17 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import dataclass
+from logging import getLogger
from typing import TYPE_CHECKING
+from opentelemetry.attributes import _clean_attribute_value
from opentelemetry.context import Context
from opentelemetry.util.types import Attributes
+_logger = getLogger(__name__)
+
if TYPE_CHECKING:
from opentelemetry.sdk.metrics._internal.instrument import _Instrument
@@ -23,7 +28,8 @@ class Measurement:
time_unix_nano: The time the API call was made to record the Measurement
instrument: The instrument that produced this `Measurement`.
context: The active Context of the Measurement at API call time.
- attributes: Measurement attributes
+ attributes: Measurement attributes. Mutating mutable attribute values (lists or dicts)
+ outside of the Measurement object can lead to undefined and bad behavior.
"""
value: int | float
@@ -31,3 +37,18 @@ class Measurement:
instrument: _Instrument
context: Context
attributes: Attributes = None
+
+ def __post_init__(self) -> None:
+ if self.attributes is not None:
+ if isinstance(self.attributes, Mapping):
+ object.__setattr__(
+ self,
+ "attributes",
+ _clean_attribute_value(self.attributes, None),
+ )
+ else:
+ _logger.warning(
+ "Invalid type '%s' for attributes. Expected a Mapping or None.",
+ type(self.attributes),
+ )
+ object.__setattr__(self, "attributes", None)
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py
index a84c9f25..36aa826c 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py
@@ -78,7 +78,7 @@ from opentelemetry.sdk.version import (
__version__ as _OPENTELEMETRY_SDK_VERSION,
)
from opentelemetry.semconv.resource import ResourceAttributes
-from opentelemetry.util.types import AttributeValue
+from opentelemetry.util.types import AnyValue
psutil: ModuleType | None = None
@@ -89,10 +89,9 @@ try:
except ImportError:
pass
-LabelValue = AttributeValue
+LabelValue = AnyValue
Attributes = Mapping[str, LabelValue]
logger = logging.getLogger(__name__)
-
CLOUD_PROVIDER = ResourceAttributes.CLOUD_PROVIDER
CLOUD_ACCOUNT_ID = ResourceAttributes.CLOUD_ACCOUNT_ID
CLOUD_REGION = ResourceAttributes.CLOUD_REGION
@@ -160,7 +159,8 @@ class Resource:
_schema_url: str
def __init__(self, attributes: Attributes, schema_url: str | None = None):
- self._attributes = BoundedAttributes(attributes=attributes)
+ # Immutable set to true so attributes cannot be added or removed after creation.
+ self._attributes = BoundedAttributes(attributes=attributes, immutable=True)
if schema_url is None:
schema_url = ""
self._schema_url = schema_url
@@ -310,7 +310,7 @@ class OTELResourceDetector(ResourceDetector):
# pylint: disable=no-self-use
def detect(self) -> "Resource":
env_resources_items = environ.get(OTEL_RESOURCE_ATTRIBUTES)
- env_resource_map: dict[str, AttributeValue] = {}
+ env_resource_map: dict[str, AnyValue] = {}
if env_resources_items:
for item in env_resources_items.split(","):
@@ -374,7 +374,7 @@ class ProcessResourceDetector(ResourceDetector):
# default because full command arguments are opt-in.
_process_command = sys.orig_argv[0] if sys.orig_argv else ""
executable = sys.executable or ""
- resource_info: dict[str, AttributeValue] = {
+ resource_info: dict[str, AnyValue] = {
PROCESS_RUNTIME_DESCRIPTION: sys.version,
PROCESS_RUNTIME_NAME: sys.implementation.name,
PROCESS_RUNTIME_VERSION: _runtime_version,
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
index 53994894..14d6573d 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
@@ -816,10 +816,12 @@ class Span(trace_api.Span, ReadableSpan):
self._events = self._new_events()
if events:
for event in events:
+ # Immutable set to true so attributes cannot be added or removed after creation.
event._attributes = BoundedAttributes(
self._limits.max_event_attributes,
event.attributes,
max_value_len=self._limits.max_attribute_length,
+ immutable=True,
)
self._events.append(event)
@@ -840,11 +842,13 @@ class Span(trace_api.Span, ReadableSpan):
valid_links = []
for link in links:
if link and _is_valid_link(link.context, link.attributes):
+ # Immutable set to true so attributes cannot be added or removed after creation.
# pylint: disable=protected-access
link._attributes = BoundedAttributes(
self._limits.max_link_attributes,
link.attributes,
max_value_len=self._limits.max_attribute_length,
+ immutable=True,
)
valid_links.append(link)
@@ -853,7 +857,7 @@ class Span(trace_api.Span, ReadableSpan):
def get_span_context(self) -> trace_api.SpanContext:
return typing.cast(trace_api.SpanContext, self._context)
- def set_attributes(self, attributes: Mapping[str, types.AttributeValue]) -> None:
+ def set_attributes(self, attributes: Mapping[str, types.AnyValue]) -> None:
with self._lock:
if self._end_time is not None:
logger.warning("Setting attribute on ended span.")
@@ -861,7 +865,7 @@ class Span(trace_api.Span, ReadableSpan):
self._attributes._set_items(attributes) # pylint: disable=protected-access
- def set_attribute(self, key: str, value: types.AttributeValue) -> None:
+ def set_attribute(self, key: str, value: types.AnyValue) -> None:
with self._lock:
if self._end_time is not None:
logger.warning("Setting attribute on ended span.")
@@ -879,10 +883,12 @@ class Span(trace_api.Span, ReadableSpan):
attributes: types.Attributes = None,
timestamp: int | None = None,
) -> None:
+ # Immutable set to true so attributes cannot be added or removed after creation.
attributes = BoundedAttributes(
self._limits.max_event_attributes,
attributes,
max_value_len=self._limits.max_attribute_length,
+ immutable=True,
)
self._add_event(
Event(
@@ -903,11 +909,12 @@ class Span(trace_api.Span, ReadableSpan):
) -> None:
if not _is_valid_link(context, attributes):
return
-
+ # Immutable set to true so attributes cannot be added or removed after creation.
attributes = BoundedAttributes(
self._limits.max_link_attributes,
attributes,
max_value_len=self._limits.max_attribute_length,
+ immutable=True,
)
self._add_link(
trace_api.Link(
@@ -1028,7 +1035,7 @@ class Span(trace_api.Span, ReadableSpan):
module = type(exception).__module__
qualname = type(exception).__qualname__
exception_type = f"{module}.{qualname}" if module and module != "builtins" else qualname
- _attributes: MutableMapping[str, types.AttributeValue] = {
+ _attributes: MutableMapping[str, types.AnyValue] = {
EXCEPTION_TYPE: exception_type,
EXCEPTION_MESSAGE: str(exception),
EXCEPTION_STACKTRACE: stacktrace,
@@ -1330,7 +1337,7 @@ class TracerProvider(trace_api.TracerProvider):
instrumenting_module_name: str,
instrumenting_library_version: str | None = None,
schema_url: str | None = None,
- attributes: types.Attributes | None = None,
+ attributes: types.Attributes = None,
) -> "trace_api.Tracer":
if self._disabled:
return NoOpTracer()
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py
index b15dcfb0..7d74a3fb 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py
@@ -25,7 +25,7 @@ class _CompositeSampler(Sampler):
trace_id: int,
name: str,
kind: SpanKind | None = None,
- attributes: Attributes | None = None,
+ attributes: Attributes = None,
links: Sequence[Link] | None = None,
trace_state: TraceState | None = None,
) -> SamplingResult:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi
index d2add7c7..1b769659 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi
@@ -25,7 +25,7 @@ from typing import (
overload,
)
-from opentelemetry.util.types import AttributesAsKey, AttributeValue
+from opentelemetry.util.types import AnyValue, AttributesAsKey
_T = TypeVar("_T")
_KT = TypeVar("_KT")
@@ -33,7 +33,7 @@ _VT = TypeVar("_VT")
def ns_to_iso_str(nanoseconds: int) -> str: ...
def get_dict_as_key(
- labels: Mapping[str, AttributeValue],
+ labels: Mapping[str, AnyValue],
) -> AttributesAsKey: ...
# pylint: disable=no-self-use
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py b/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py
index 3f999d80..710bd81d 100644
--- a/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py
@@ -10,7 +10,6 @@ from opentelemetry.attributes import BoundedAttributes
from opentelemetry.util.types import ( # TODO: see if we can remove F401 when using new sphinx version # noqa: F401 # pylint: disable=unused-import
AnyValue,
Attributes,
- _ExtendedAttributes,
)
@@ -86,14 +85,15 @@ class InstrumentationScope:
name: str,
version: str | None = None,
schema_url: str | None = None,
- attributes: _ExtendedAttributes | None = None,
+ attributes: Attributes = None,
) -> None:
self._name = name
self._version = version
if schema_url is None:
schema_url = ""
self._schema_url = schema_url
- self._attributes = BoundedAttributes(attributes=attributes)
+ # Attributes cannot be added/removed after creation.
+ self._attributes = BoundedAttributes(attributes=attributes, immutable=True)
def __repr__(self) -> str:
return f"{type(self).__name__}({self._name}, {self._version}, {self._schema_url}, {self._attributes})"
diff --git a/opentelemetry-sdk/tests/logs/test_logs.py b/opentelemetry-sdk/tests/logs/test_logs.py
index 47fa09e2..171a680b 100644
--- a/opentelemetry-sdk/tests/logs/test_logs.py
+++ b/opentelemetry-sdk/tests/logs/test_logs.py
@@ -446,7 +446,6 @@ class TestLogger(unittest.TestCase):
original_attributes = BoundedAttributes(
attributes={"custom": "value"},
immutable=True,
- extended_attributes=True,
)
log_record = LogRecord(
observed_timestamp=0,
diff --git a/opentelemetry-sdk/tests/metrics/test_metrics.py b/opentelemetry-sdk/tests/metrics/test_metrics.py
index b84088a5..d093873e 100644
--- a/opentelemetry-sdk/tests/metrics/test_metrics.py
+++ b/opentelemetry-sdk/tests/metrics/test_metrics.py
@@ -41,6 +41,7 @@ from opentelemetry.sdk.metrics._internal import (
_ProxyMeterConfig,
_RuleBasedMeterConfigurator,
)
+from opentelemetry.sdk.metrics._internal.measurement import Measurement
from opentelemetry.sdk.metrics.export import (
InMemoryMetricReader,
Metric,
@@ -988,3 +989,49 @@ class TestDuplicateInstrumentAggregateData(TestCase):
self.assertEqual(metric_1.unit, "unit")
self.assertEqual(metric_1.description, "description")
self.assertEqual(next(iter(metric_1.data.data_points)).value, 7)
+
+
+class TestMeasurement(TestCase):
+ def test_measurement_attributes_cleaned(self):
+ measurement = Measurement(
+ value=10,
+ time_unix_nano=0,
+ instrument=Mock(),
+ context=Mock(),
+ attributes={"a": "b", 1: 2, "seq": [1, 2]},
+ )
+ self.assertEqual(
+ measurement.attributes,
+ {"a": "b", "1": 2, "seq": (1, 2)},
+ )
+
+ def test_measurement_attributes_invalid_type(self):
+ with self.assertLogs(level=WARNING) as logs:
+ measurement = Measurement(
+ value=10,
+ time_unix_nano=0,
+ instrument=Mock(),
+ context=Mock(),
+ attributes="invalid",
+ )
+ self.assertIsNone(measurement.attributes)
+ self.assertIn("Invalid type", logs.output[0])
+
+ def test_measurement_attributes_none_or_empty(self):
+ m1 = Measurement(
+ value=10,
+ time_unix_nano=0,
+ instrument=Mock(),
+ context=Mock(),
+ attributes=None,
+ )
+ self.assertIsNone(m1.attributes)
+
+ m2 = Measurement(
+ value=10,
+ time_unix_nano=0,
+ instrument=Mock(),
+ context=Mock(),
+ attributes={},
+ )
+ self.assertEqual(m2.attributes, {})
diff --git a/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py b/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py
index 6ea757c1..8985a339 100644
--- a/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py
+++ b/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py
@@ -11,6 +11,7 @@ from unittest.mock import MagicMock, Mock, patch
from opentelemetry.context import Context
from opentelemetry.sdk.metrics._internal._view_instrument_match import (
+ _hash_attributes,
_ViewInstrumentMatch,
)
from opentelemetry.sdk.metrics._internal.aggregation import (
@@ -97,7 +98,7 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
)
self.assertEqual(
view_instrument_match._attributes_aggregation,
- {frozenset([("c", "d")]): self.mock_created_aggregation},
+ {_hash_attributes({"c": "d"}): self.mock_created_aggregation},
)
view_instrument_match.consume_measurement(
@@ -113,12 +114,13 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
self.assertEqual(
view_instrument_match._attributes_aggregation,
{
- frozenset(): self.mock_created_aggregation,
- frozenset([("c", "d")]): self.mock_created_aggregation,
+ _hash_attributes({}): self.mock_created_aggregation,
+ _hash_attributes({"c": "d"}): self.mock_created_aggregation,
},
)
- # None attribute_keys (default) will keep all attributes
+ # setup new instrument match without `attribute_keys` set, defaults to keeping
+ # all attributes.
view_instrument_match = _ViewInstrumentMatch(
view=View(
instrument_name="instrument1",
@@ -140,10 +142,10 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
)
self.assertEqual(
view_instrument_match._attributes_aggregation,
- {frozenset([("c", "d"), ("f", "g")]): self.mock_created_aggregation},
+ {_hash_attributes({"c": "d", "f": "g"}): self.mock_created_aggregation},
)
- # empty set attribute_keys will drop all labels and aggregate
+ # empty set attribute_keys will drop all attributes and aggregate
# everything together
view_instrument_match = _ViewInstrumentMatch(
view=View(
@@ -161,12 +163,12 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
time_unix_nano=time_ns(),
instrument=instrument1,
context=Context(),
- attributes=None,
+ attributes={"a": 1, "b": 2},
)
)
self.assertEqual(
view_instrument_match._attributes_aggregation,
- {frozenset({}): self.mock_created_aggregation},
+ {_hash_attributes({}): self.mock_created_aggregation},
)
# Test that a drop aggregation is handled in the same way as any
@@ -193,7 +195,7 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
)
)
self.assertIsInstance(
- view_instrument_match._attributes_aggregation[frozenset({})],
+ view_instrument_match._attributes_aggregation[_hash_attributes({})],
_DropAggregation,
)
@@ -238,6 +240,8 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
def test_consume_measurement_attributes_are_copied(self):
"""Mutating the attributes dict after recording must not affect stored data points."""
+ # Note mutating mutable objects in the attributes dict will still cause issues,
+ # as they are not deep copied.
instrument1 = _Counter(
"instrument1",
Mock(),
@@ -269,11 +273,13 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
# Mutate the original dict after recording
attributes["key"] = "mutated"
-
number_data_points = view_instrument_match.collect(AggregationTemporality.CUMULATIVE, 0)
number_data_points = list(number_data_points)
self.assertEqual(len(number_data_points), 1)
- self.assertEqual(number_data_points[0].attributes, {"key": "original"})
+ self.assertEqual(
+ number_data_points[0].attributes,
+ {"key": "original"},
+ )
@patch(
"opentelemetry.sdk.metrics._internal._view_instrument_match.time_ns",
@@ -488,10 +494,166 @@ class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name
)
self.assertIsInstance(
- view_instrument_match._attributes_aggregation[frozenset({("c", "d")})],
+ view_instrument_match._attributes_aggregation[_hash_attributes({"c": "d"})],
_LastValueAggregation,
)
+ def test_hash_attributes_works_as_stable_hash_key(self):
+ attributes = {
+ "a": [1, 2],
+ "b": [2, 1],
+ "c": b"1234asf",
+ "d": 1.2324124,
+ "e": -2.32323124,
+ "f": {1: 2, 2: (1, 2, 3), 3: "a", 4: "bc"},
+ }
+ self.assertEqual(
+ _hash_attributes(attributes),
+ _hash_attributes(attributes),
+ )
+
+ self.assertNotEqual(
+ _hash_attributes({"1": (1, "2", 3, "4")}),
+ _hash_attributes({"1": ("1", 2, "3", 4)}),
+ )
+
+ def test_hash_attributes_stable_hash_key_order_independence(self):
+ attrs1 = {"b": 2, "a": 1, "c": 3}
+ attrs2 = {"a": 1, "c": 3, "b": 2}
+ self.assertEqual(
+ _hash_attributes(attrs1),
+ _hash_attributes(attrs2),
+ )
+
+ nested1 = {"root": {"z": (3, 2, 1), "x": "val", "y": b"bytes_data"}}
+ nested2 = {"root": {"y": b"bytes_data", "z": (3, 2, 1), "x": "val"}}
+ self.assertEqual(
+ _hash_attributes(nested1),
+ _hash_attributes(nested2),
+ )
+
+ def test_hash_attributes_stable_hash_with_tuples_and_nested_dicts(self):
+ complex_attrs_a = {
+ "service": {"name": "test-svc", "version": "1.0"},
+ "tags": ("prod", "us-east-1"),
+ "endpoints": (
+ {"host": "a.com", "port": 80},
+ {"host": "b.com", "port": 443},
+ ),
+ "payload": b"binary-content",
+ }
+ complex_attrs_b = {
+ "payload": b"binary-content",
+ "endpoints": (
+ {"port": 80, "host": "a.com"},
+ {"port": 443, "host": "b.com"},
+ ),
+ "service": {"version": "1.0", "name": "test-svc"},
+ "tags": ("prod", "us-east-1"),
+ }
+ self.assertEqual(
+ _hash_attributes(complex_attrs_a),
+ _hash_attributes(complex_attrs_b),
+ )
+
+ def test_hash_attributes_tuple_and_list_equivalence(self):
+ attrs_tuple = {"values": (1, 2, 3), "nested": {"items": ("a", "b")}}
+ attrs_list = {"values": [1, 2, 3], "nested": {"items": ["a", "b"]}}
+ self.assertEqual(
+ _hash_attributes(attrs_tuple),
+ _hash_attributes(attrs_list),
+ )
+
+ def test_consume_measurement_with_non_string_keys(self):
+ instrument1 = _Counter(
+ name="instrument1",
+ instrumentation_scope=Mock(),
+ measurement_consumer=Mock(),
+ description="description",
+ unit="unit",
+ )
+ instrument1.instrumentation_scope = self.mock_instrumentation_scope
+ view_instrument_match = _ViewInstrumentMatch(
+ view=View(
+ instrument_name="instrument1",
+ name="name",
+ aggregation=DefaultAggregation(),
+ ),
+ instrument=instrument1,
+ instrument_class_aggregation={_Counter: LastValueAggregation()},
+ )
+
+ attributes = {"c": 1, 22: 3, (1,): 2}
+
+ measurement = Measurement(
+ value=0,
+ time_unix_nano=time_ns(),
+ instrument=Mock(name="instrument1"),
+ context=Context(),
+ attributes=attributes,
+ )
+ view_instrument_match.consume_measurement(measurement)
+ self.assertEqual(
+ measurement.attributes,
+ {"c": 1, "22": 3, "(1,)": 2},
+ )
+ self.assertIn(
+ _hash_attributes(measurement.attributes),
+ view_instrument_match._attributes_aggregation,
+ )
+
+ def test_consume_measurement_stable_hash_key_order(self):
+ instrument1 = _Counter(
+ "instrument1",
+ Mock(),
+ Mock(),
+ description="description",
+ unit="unit",
+ )
+ instrument1.instrumentation_scope = self.mock_instrumentation_scope
+ view_instrument_match = _ViewInstrumentMatch(
+ view=View(
+ instrument_name="instrument1",
+ name="name",
+ aggregation=DefaultAggregation(),
+ ),
+ instrument=instrument1,
+ instrument_class_aggregation=MagicMock(**{"__getitem__.return_value": DefaultAggregation()}),
+ )
+
+ attrs1 = {
+ "service": {"version": "1.0", "name": "app"},
+ "tags": ("prod", "v1"),
+ "region": "us-east-1",
+ }
+ attrs2 = {
+ "region": "us-east-1",
+ "tags": ("prod", "v1"),
+ "service": {"name": "app", "version": "1.0"},
+ }
+ view_instrument_match.consume_measurement(
+ Measurement(
+ value=1,
+ time_unix_nano=time_ns(),
+ instrument=instrument1,
+ context=Context(),
+ attributes=attrs1,
+ )
+ )
+ view_instrument_match.consume_measurement(
+ Measurement(
+ value=2,
+ time_unix_nano=time_ns(),
+ instrument=instrument1,
+ context=Context(),
+ attributes=attrs2,
+ )
+ )
+
+ self.assertEqual(len(view_instrument_match._attributes_aggregation), 1)
+ expected_key = _hash_attributes(attrs1)
+ self.assertIn(expected_key, view_instrument_match._attributes_aggregation)
+
class TestSimpleFixedSizeExemplarReservoir(TestCase):
def test_consume_measurement_with_custom_reservoir_factory(self):
diff --git a/opentelemetry-sdk/tests/resources/test_resources.py b/opentelemetry-sdk/tests/resources/test_resources.py
index 282611dd..973b9685 100644
--- a/opentelemetry-sdk/tests/resources/test_resources.py
+++ b/opentelemetry-sdk/tests/resources/test_resources.py
@@ -251,24 +251,29 @@ class TestResources(unittest.TestCase):
)
def test_invalid_resource_attribute_values(self):
+ # This class has no __str__ or __repr__ method, so BoundedAttributes does
+ # not attempt to convert it to a string and defaults to returning None.
+ class NoStrNoRepr:
+ def __init__(self):
+ pass
+
+ # Empty key will get dropped.
with self.assertLogs(level=WARNING):
resource = Resource(
{
SERVICE_NAME: "test",
- "non-primitive-data-type": {},
- "invalid-byte-type-attribute": (b"\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1"),
+ "bad-type": NoStrNoRepr(),
"": "empty-key-value",
- None: "null-key-value",
- "another-non-primitive": uuid.uuid4(),
}
)
self.assertEqual(
resource.attributes,
{
SERVICE_NAME: "test",
+ "bad-type": None,
},
)
- self.assertEqual(len(resource.attributes), 1)
+ self.assertEqual(len(resource.attributes), 2)
def test_aggregated_resources_no_detectors(self):
aggregated_resources = get_aggregated_resources([])
diff --git a/opentelemetry-sdk/tests/trace/test_trace.py b/opentelemetry-sdk/tests/trace/test_trace.py
index c139e44e..81728a08 100644
--- a/opentelemetry-sdk/tests/trace/test_trace.py
+++ b/opentelemetry-sdk/tests/trace/test_trace.py
@@ -857,7 +857,12 @@ class TestSpan(unittest.TestCase):
root.set_attribute("http.response.status_code", 200)
root.set_attribute("http.status_text", "OK")
root.set_attribute("misc.pi", 3.14)
-
+ root.set_attribute("mapping-key", {"key": "value"})
+ root.set_attribute("array-key", [1, 2, 3])
+ root.set_attribute(
+ "complex-key",
+ [{"key1": "value1"}, {"key2": 42}, "key3", [1, 2, 3]],
+ )
# Setting an attribute with the same key as an existing attribute
# SHOULD overwrite the existing attribute's value.
root.set_attribute("attr-key", "attr-value1")
@@ -869,7 +874,7 @@ class TestSpan(unittest.TestCase):
list_of_numerics = [123, 314, 0]
root.set_attribute("list-of-numerics", list_of_numerics)
- self.assertEqual(len(root.attributes), 9)
+ self.assertEqual(len(root.attributes), 12)
self.assertEqual(root.attributes["http.request.method"], "GET")
self.assertEqual(
root.attributes["url.full"],
@@ -899,46 +904,29 @@ class TestSpan(unittest.TestCase):
self.assertEqual(root.attributes["attr-in-both"], "span-attr")
def test_invalid_attribute_values(self):
- with self.tracer.start_as_current_span("root") as root:
- with self.assertLogs(level=WARNING):
- root.set_attributes({"correct-value": "foo", "non-primitive-data-type": {}})
+ # This class has no __str__ or __repr__ method, so BoundedAttributes does
+ # not attempt to convert it to a string and defaults to returning None.
+ class NoStrNoRepr:
+ def __init__(self):
+ pass
+ with self.tracer.start_as_current_span("root") as root:
with self.assertLogs(level=WARNING):
- root.set_attribute("non-primitive-data-type", {})
- with self.assertLogs(level=WARNING):
- root.set_attribute(
- "list-of-mixed-data-types-numeric-first",
- [123, False, "string"],
- )
- with self.assertLogs(level=WARNING):
- root.set_attribute(
- "list-of-mixed-data-types-non-numeric-first",
- [False, 123, "string"],
+ root.set_attributes(
+ {
+ "correct-value": "foo",
+ "bad-type": NoStrNoRepr(),
+ }
)
- with self.assertLogs(level=WARNING):
- root.set_attribute("list-with-non-primitive-data-type", [{}, 123])
- with self.assertLogs(level=WARNING):
- root.set_attribute("list-with-numeric-and-bool", [1, True])
- with self.assertLogs(level=WARNING):
- root.set_attribute("", 123)
- with self.assertLogs(level=WARNING):
- root.set_attribute(None, 123)
-
- self.assertEqual(len(root.attributes), 1)
+ self.assertEqual(len(root.attributes), 2)
self.assertEqual(root.attributes["correct-value"], "foo")
+ self.assertIsNone(root.attributes["bad-type"])
def test_byte_type_attribute_value(self):
with self.tracer.start_as_current_span("root") as root:
- with self.assertLogs(level=WARNING):
- root.set_attribute(
- "invalid-byte-type-attribute",
- b"\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1",
- )
- self.assertFalse("invalid-byte-type-attribute" in root.attributes)
-
root.set_attribute("valid-byte-type-attribute", b"valid byte")
- self.assertTrue(isinstance(root.attributes["valid-byte-type-attribute"], str))
+ self.assertTrue(isinstance(root.attributes["valid-byte-type-attribute"], bytes))
def test_sampling_attributes(self):
sampling_attributes = {
@@ -1014,24 +1002,23 @@ class TestSpan(unittest.TestCase):
with self.assertRaises(TypeError):
event.attributes["name"] = "hello"
- def test_invalid_event_attributes(self):
+ def test_setting_event_attributes(self):
self.assertEqual(trace_api.get_current_span(), trace_api.INVALID_SPAN)
with self.tracer.start_as_current_span("root") as root:
- with self.assertLogs(level=WARNING):
- root.add_event("event0", {"attr1": True, "attr2": ["hi", False]})
- with self.assertLogs(level=WARNING):
- root.add_event("event0", {"attr1": {}})
- with self.assertLogs(level=WARNING):
- root.add_event("event0", {"attr1": [[True]]})
- with self.assertLogs(level=WARNING):
- root.add_event("event0", {"attr1": [{}], "attr2": [1, 2]})
+ root.add_event("event0", {"attr1": True, "attr2": ["hi", False]})
+ root.add_event("event0", {"attr1": {}})
+ root.add_event("event0", {"attr1": [[True]]})
+ root.add_event("event0", {"attr1": [{}], "attr2": [1, 2]})
self.assertEqual(len(root.events), 4)
- self.assertEqual(root.events[0].attributes, {"attr1": True})
- self.assertEqual(root.events[1].attributes, {})
- self.assertEqual(root.events[2].attributes, {})
- self.assertEqual(root.events[3].attributes, {"attr2": (1, 2)})
+ self.assertEqual(
+ root.events[0].attributes,
+ {"attr1": True, "attr2": ("hi", False)},
+ )
+ self.assertEqual(root.events[1].attributes, {"attr1": {}})
+ self.assertEqual(root.events[2].attributes, {"attr1": ((True,),)})
+ self.assertEqual(root.events[3].attributes, {"attr2": (1, 2), "attr1": ({},)})
def test_links(self):
id_generator = RandomIdGenerator()
diff --git a/pyproject.toml b/pyproject.toml
index f7727d38..49039550 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -173,6 +173,7 @@ strict = [
"opentelemetry-semantic-conventions",
"opentelemetry-sdk/src/opentelemetry/sdk/environment_variables",
"opentelemetry-sdk/src/opentelemetry/sdk/resources",
+ "opentelemetry-api/src/opentelemetry/attributes/__init__.py",
]
[tool.datamodel-codegen]
|