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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif os(Windows)
import CRT
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
import WASILibc
#else
#error("Unsupported runtime")
#endif
/// A `Logger` is the central type in `SwiftLog`. Its central function is to emit log messages using one of the methods
/// corresponding to a log level.
///
/// `Logger`s are value types with respect to the ``logLevel`` and the ``metadata`` (as well as the immutable `label`
/// and the selected ``LogHandler``). Therefore, `Logger`s are suitable to be passed around between libraries if you want
/// to preserve metadata across libraries.
///
/// The most basic usage of a `Logger` is
///
/// ```swift
/// logger.info("Hello World!")
/// ```
public struct Logger {
@usableFromInline
var handler: LogHandler
/// An identifier of the creator of this `Logger`.
public let label: String
/// The metadata provider this logger was created with.
public var metadataProvider: Logger.MetadataProvider? {
return self.handler.metadataProvider
}
internal init(label: String, _ handler: LogHandler) {
self.label = label
self.handler = handler
}
}
extension Logger {
#if compiler(>=5.3)
/// Log a message passing the log level as a parameter.
///
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
if self.logLevel <= level {
self.handler.log(level: level,
message: message(),
metadata: metadata(),
source: source() ?? Logger.currentModule(fileID: (file)),
file: file, function: function, line: line)
}
}
#else
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
if self.logLevel <= level {
self.handler.log(level: level,
message: message(),
metadata: metadata(),
source: source() ?? Logger.currentModule(filePath: (file)),
file: file, function: function, line: line)
}
}
#endif
/// Log a message passing the log level as a parameter.
///
/// If the ``logLevel`` passed to this method is more severe than the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: level, message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: level, message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Add, change, or remove a logging metadata item.
///
/// - note: Logging metadata behaves as a value that means a change to the logging metadata will only affect the
/// very `Logger` it was changed on.
@inlinable
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.handler[metadataKey: metadataKey]
}
set {
self.handler[metadataKey: metadataKey] = newValue
}
}
/// Get or set the log level configured for this `Logger`.
///
/// - note: `Logger`s treat `logLevel` as a value. This means that a change in `logLevel` will only affect this
/// very `Logger`. It is acceptable for logging backends to have some form of global log level override
/// that affects multiple or even all loggers. This means a change in `logLevel` to one `Logger` might in
/// certain cases have no effect.
@inlinable
public var logLevel: Logger.Level {
get {
return self.handler.logLevel
}
set {
self.handler.logLevel = newValue
}
}
}
extension Logger {
/// Log a message passing with the ``Logger/Level/trace`` log level.
///
/// If `.trace` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func trace(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .trace, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func trace(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .trace, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/trace`` log level.
///
/// If `.trace` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func trace(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.trace(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func trace(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.trace(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/debug`` log level.
///
/// If `.debug` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .debug, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .debug, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/debug`` log level.
///
/// If `.debug` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.debug(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.debug(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/info`` log level.
///
/// If `.info` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .info, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .info, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/info`` log level.
///
/// If `.info` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.info(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.info(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/notice`` log level.
///
/// If `.notice` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .notice, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .notice, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/notice`` log level.
///
/// If `.notice` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.notice(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.notice(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/warning`` log level.
///
/// If `.warning` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .warning, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .warning, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/warning`` log level.
///
/// If `.warning` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.warning(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.warning(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/error`` log level.
///
/// If `.error` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .error, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .error, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/error`` log level.
///
/// If `.error` is at least as severe as the `Logger`'s ``logLevel``, it will be logged,
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.error(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.error(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/critical`` log level.
///
/// `.critical` messages will always be logged.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .critical, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: .critical, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#endif
/// Log a message passing with the ``Logger/Level/critical`` log level.
///
/// `.critical` messages will always be logged.
///
/// - parameters:
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log messages originates from. Defaults
/// to the module emitting the log message (on Swift 5.3 or
/// newer and the folder name containing the log emitting file on Swift 5.2 or
/// older).
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#fileID` (on Swift 5.3 or newer and `#file` on Swift 5.2 or older).
/// - function: The function this log message originates from (there's usually no need to pass it explicitly as
/// it defaults to `#function`).
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
#if compiler(>=5.3)
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.critical(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#else
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.critical(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
#endif
}
/// The `LoggingSystem` is a global facility where the default logging backend implementation (`LogHandler`) can be
/// configured. `LoggingSystem` is set up just once in a given program to set up the desired logging backend
/// implementation.
public enum LoggingSystem {
private static let _factory = FactoryBox { label, _ in StreamLogHandler.standardOutput(label: label) }
private static let _metadataProviderFactory = MetadataProviderBox(nil)
#if DEBUG
private static var _warnOnceBox: WarnOnceBox = WarnOnceBox()
#endif
/// `bootstrap` is a one-time configuration function which globally selects the desired logging backend
/// implementation. `bootstrap` can be called at maximum once in any given program, calling it more than once will
/// lead to undefined behavior, most likely a crash.
///
/// - parameters:
/// - factory: A closure that given a `Logger` identifier, produces an instance of the `LogHandler`.
public static func bootstrap(_ factory: @escaping (String) -> LogHandler) {
self._factory.replaceFactory({ label, _ in
factory(label)
}, validate: true)
}
/// `bootstrap` is a one-time configuration function which globally selects the desired logging backend
/// implementation.
///
/// - Warning:
/// `bootstrap` can be called at maximum once in any given program, calling it more than once will
/// lead to undefined behavior, most likely a crash.
///
/// - parameters:
/// - metadataProvider: The `MetadataProvider` used to inject runtime-generated metadata from the execution context.
/// - factory: A closure that given a `Logger` identifier, produces an instance of the `LogHandler`.
public static func bootstrap(_ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler,
metadataProvider: Logger.MetadataProvider?) {
self._metadataProviderFactory.replaceMetadataProvider(metadataProvider, validate: true)
self._factory.replaceFactory(factory, validate: true)
}
// for our testing we want to allow multiple bootstrapping
internal static func bootstrapInternal(_ factory: @escaping (String) -> LogHandler) {
self._metadataProviderFactory.replaceMetadataProvider(nil, validate: false)
self._factory.replaceFactory({ label, _ in
factory(label)
}, validate: false)
}
// for our testing we want to allow multiple bootstrapping
internal static func bootstrapInternal(_ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler,
metadataProvider: Logger.MetadataProvider?) {
self._metadataProviderFactory.replaceMetadataProvider(metadataProvider, validate: false)
self._factory.replaceFactory(factory, validate: false)
}
fileprivate static var factory: (String, Logger.MetadataProvider?) -> LogHandler {
return { label, metadataProvider in
self._factory.underlying(label, metadataProvider)
}
}
/// System wide ``Logger/MetadataProvider`` that was configured during the logging system's `bootstrap`.
///
/// When creating a ``Logger`` using the plain ``Logger/init(label:)`` initializer, this metadata provider
/// will be provided to it.
///
/// When using custom log handler factories, make sure to provide the bootstrapped metadata provider to them,
/// or the metadata will not be filled in automatically using the provider on log-sites. While using a custom
/// factory to avoid using the bootstrapped metadata provider may sometimes be useful, usually it will lead to
/// un-expected behavior, so make sure to always propagate it to your handlers.
public static var metadataProvider: Logger.MetadataProvider? {
return self._metadataProviderFactory.metadataProvider
}
#if DEBUG
/// Used to warn only once about a specific ``LogHandler`` type when it does not support ``Logger/MetadataProvider``,
/// but an attempt was made to set a metadata provider on such handler. In order to avoid flooding the system with
/// warnings such warning is only emitted in debug mode, and even then at-most once for a handler type.
internal static func warnOnceLogHandlerNotSupportedMetadataProvider<Handler: LogHandler>(_ type: Handler.Type) -> Bool {
self._warnOnceBox.warnOnceLogHandlerNotSupportedMetadataProvider(type: type)
}
#endif
private final class FactoryBox {
private let lock = ReadWriteLock()
fileprivate var _underlying: (_ label: String, _ provider: Logger.MetadataProvider?) -> LogHandler
private var initialized = false
init(_ underlying: @escaping (String, Logger.MetadataProvider?) -> LogHandler) {
self._underlying = underlying
}
func replaceFactory(_ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler, validate: Bool) {
self.lock.withWriterLock {
precondition(!validate || !self.initialized, "logging system can only be initialized once per process.")
self._underlying = factory
self.initialized = true
}
}
var underlying: (String, Logger.MetadataProvider?) -> LogHandler {
return self.lock.withReaderLock {
return self._underlying
}
}
}
private final class MetadataProviderBox {
private let lock = ReadWriteLock()
internal var _underlying: Logger.MetadataProvider?
private var initialized = false
init(_ underlying: Logger.MetadataProvider?) {
self._underlying = underlying
}
func replaceMetadataProvider(_ metadataProvider: Logger.MetadataProvider?, validate: Bool) {
self.lock.withWriterLock {
precondition(!validate || !self.initialized, "logging system can only be initialized once per process.")
self._underlying = metadataProvider
self.initialized = true
}
}
var metadataProvider: Logger.MetadataProvider? {
return self.lock.withReaderLock {
return self._underlying
}
}
}
}
extension Logger {
/// `Metadata` is a typealias for `[String: Logger.MetadataValue]` the type of the metadata storage.
public typealias Metadata = [String: MetadataValue]
/// A logging metadata value. `Logger.MetadataValue` is string, array, and dictionary literal convertible.
///
/// `MetadataValue` provides convenient conformances to `ExpressibleByStringInterpolation`,
/// `ExpressibleByStringLiteral`, `ExpressibleByArrayLiteral`, and `ExpressibleByDictionaryLiteral` which means
/// that when constructing `MetadataValue`s you should default to using Swift's usual literals.
///
/// Examples:
/// - prefer `logger.info("user logged in", metadata: ["user-id": "\(user.id)"])` over
/// `..., metadata: ["user-id": .string(user.id.description)])`
/// - prefer `logger.info("user selected colors", metadata: ["colors": ["\(user.topColor)", "\(user.secondColor)"]])`
/// over `..., metadata: ["colors": .array([.string("\(user.topColor)"), .string("\(user.secondColor)")])`
/// - prefer `logger.info("nested info", metadata: ["nested": ["fave-numbers": ["\(1)", "\(2)", "\(3)"], "foo": "bar"]])`
/// over `..., metadata: ["nested": .dictionary(["fave-numbers": ...])])`
public enum MetadataValue {
/// A metadata value which is a `String`.
///
/// Because `MetadataValue` implements `ExpressibleByStringInterpolation`, and `ExpressibleByStringLiteral`,
/// you don't need to type `.string(someType.description)` you can use the string interpolation `"\(someType)"`.
case string(String)
/// A metadata value which is some `CustomStringConvertible`.
#if compiler(>=5.7)
case stringConvertible(CustomStringConvertible & Sendable)
#else
case stringConvertible(CustomStringConvertible)
#endif
/// A metadata value which is a dictionary from `String` to `Logger.MetadataValue`.
///
/// Because `MetadataValue` implements `ExpressibleByDictionaryLiteral`, you don't need to type
/// `.dictionary(["foo": .string("bar \(buz)")])`, you can just use the more natural `["foo": "bar \(buz)"]`.
case dictionary(Metadata)
/// A metadata value which is an array of `Logger.MetadataValue`s.
///
/// Because `MetadataValue` implements `ExpressibleByArrayLiteral`, you don't need to type
/// `.array([.string("foo"), .string("bar \(buz)")])`, you can just use the more natural `["foo", "bar \(buz)"]`.
case array([Metadata.Value])
}
/// The log level.
///
/// Log levels are ordered by their severity, with `.trace` being the least severe and
/// `.critical` being the most severe.
public enum Level: String, Codable, CaseIterable {
/// Appropriate for messages that contain information normally of use only when
/// tracing the execution of a program.
case trace
/// Appropriate for messages that contain information normally of use only when
/// debugging a program.
case debug
/// Appropriate for informational messages.
case info
/// Appropriate for conditions that are not error conditions, but that may require
/// special handling.
case notice
/// Appropriate for messages that are not error conditions, but more severe than
/// `.notice`.
case warning
/// Appropriate for error conditions.
case error
/// Appropriate for critical error conditions that usually require immediate
/// attention.
///
/// When a `critical` message is logged, the logging backend (`LogHandler`) is free to perform
/// more heavy-weight operations to capture system state (such as capturing stack traces) to facilitate
/// debugging.
case critical
}
/// Construct a `Logger` given a `label` identifying the creator of the `Logger`.
///
/// The `label` should identify the creator of the `Logger`. This can be an application, a sub-system, or even
/// a datatype.
///
/// - parameters:
/// - label: An identifier for the creator of a `Logger`.
public init(label: String) {
self.init(label: label, LoggingSystem.factory(label, LoggingSystem.metadataProvider))
}
/// Construct a `Logger` given a `label` identifying the creator of the `Logger` or a non-standard `LogHandler`.
///
/// The `label` should identify the creator of the `Logger`. This can be an application, a sub-system, or even
/// a datatype.
///
/// This initializer provides an escape hatch in case the global default logging backend implementation (set up
/// using `LoggingSystem.bootstrap` is not appropriate for this particular logger.
///
/// - parameters:
/// - label: An identifier for the creator of a `Logger`.
/// - factory: A closure creating non-standard `LogHandler`s.
public init(label: String, factory: (String) -> LogHandler) {
self = Logger(label: label, factory(label))
}
/// Construct a `Logger` given a `label` identifying the creator of the `Logger` or a non-standard `LogHandler`.
///
/// The `label` should identify the creator of the `Logger`. This can be an application, a sub-system, or even
/// a datatype.
///
/// This initializer provides an escape hatch in case the global default logging backend implementation (set up
/// using `LoggingSystem.bootstrap` is not appropriate for this particular logger.
///
/// - parameters:
/// - label: An identifier for the creator of a `Logger`.
/// - factory: A closure creating non-standard `LogHandler`s.
public init(label: String, factory: (String, Logger.MetadataProvider?) -> LogHandler) {
self = Logger(label: label, factory(label, LoggingSystem.metadataProvider))
}
/// Construct a `Logger` given a `label` identifying the creator of the `Logger` and a non-standard ``Logger/MetadataProvider``.
///
/// The `label` should identify the creator of the `Logger`. This can be an application, a sub-system, or even
/// a datatype.
///
/// This initializer provides an escape hatch in case the global default logging backend implementation (set up
/// using `LoggingSystem.bootstrap` is not appropriate for this particular logger.
///
/// - parameters:
/// - label: An identifier for the creator of a `Logger`.
/// - metadataProvider: The custom metadata provider this logger should invoke,
/// instead of the system wide bootstrapped one, when a log statement is about to be emitted.
public init(label: String, metadataProvider: MetadataProvider) {
self = Logger(label: label, factory: { label in
var handler = LoggingSystem.factory(label, metadataProvider)
handler.metadataProvider = metadataProvider
return handler
})
}
}
extension Logger.Level {
internal var naturalIntegralValue: Int {
switch self {
case .trace:
return 0
case .debug:
return 1
case .info:
return 2
case .notice:
return 3
case .warning:
return 4
case .error:
return 5
case .critical:
return 6
}
}
}
extension Logger.Level: Comparable {
public static func < (lhs: Logger.Level, rhs: Logger.Level) -> Bool {
return lhs.naturalIntegralValue < rhs.naturalIntegralValue
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9687
// Then we could write it as follows and it would work under Swift 5 and not only 4 as it does currently:
// extension Logger.Metadata.Value: Equatable {
extension Logger.MetadataValue: Equatable {
public static func == (lhs: Logger.Metadata.Value, rhs: Logger.Metadata.Value) -> Bool {
switch (lhs, rhs) {
case (.string(let lhs), .string(let rhs)):
return lhs == rhs
case (.stringConvertible(let lhs), .stringConvertible(let rhs)):
return lhs.description == rhs.description
case (.array(let lhs), .array(let rhs)):
return lhs == rhs
case (.dictionary(let lhs), .dictionary(let rhs)):
return lhs == rhs
default:
return false
}
}
}
extension Logger {
/// `Logger.Message` represents a log message's text. It is usually created using string literals.
///
/// Example creating a `Logger.Message`:
///
/// let world: String = "world"
/// let myLogMessage: Logger.Message = "Hello \(world)"
///
/// Most commonly, `Logger.Message`s appear simply as the parameter to a logging method such as:
///
/// logger.info("Hello \(world)")
///
public struct Message: ExpressibleByStringLiteral, Equatable, CustomStringConvertible, ExpressibleByStringInterpolation {
public typealias StringLiteralType = String
private var value: String
public init(stringLiteral value: String) {
self.value = value
}
public var description: String {
return self.value
}
}
}
/// A pseudo-`LogHandler` that can be used to send messages to multiple other `LogHandler`s.
///
/// ### Effective Logger.Level
///
/// When first initialized the multiplex log handlers' log level is automatically set to the minimum of all the
/// passed in log handlers. This ensures that each of the handlers will be able to log at their appropriate level
/// any log events they might be interested in.
///
/// Example:
/// If log handler `A` is logging at `.debug` level, and log handler `B` is logging at `.info` level, the constructed
/// `MultiplexLogHandler([A, B])`'s effective log level will be set to `.debug`, meaning that debug messages will be
/// handled by this handler, while only logged by the underlying `A` log handler (since `B`'s log level is `.info`
/// and thus it would not actually log that log message).
///
/// If the log level is _set_ on a `Logger` backed by an `MultiplexLogHandler` the log level will apply to *all*
/// underlying log handlers, allowing a logger to still select at what level it wants to log regardless of if the underlying
/// handler is a multiplex or a normal one. If for some reason one might want to not allow changing a log level of a specific
/// handler passed into the multiplex log handler, this is possible by wrapping it in a handler which ignores any log level changes.
///
/// ### Effective Logger.Metadata
///
/// Since a `MultiplexLogHandler` is a combination of multiple log handlers, the handling of metadata can be non-obvious.
/// For example, the underlying log handlers may have metadata of their own set before they are used to initialize the multiplex log handler.
///
/// The multiplex log handler acts purely as proxy and does not make any changes to underlying handler metadata other than
/// proxying writes that users made on a `Logger` instance backed by this handler.
///
/// Setting metadata is always proxied through to _all_ underlying handlers, meaning that if a modification like
/// `logger[metadataKey: "x"] = "y"` is made, all underlying log handlers that this multiplex handler was initiated with
/// will observe this change.
///
/// Reading metadata from the multiplex log handler MAY need to pick one of conflicting values if the underlying log handlers
/// were already initiated with some metadata before passing them into the multiplex handler. The multiplex handler uses
/// the order in which the handlers were passed in during its initialization as a priority indicator - the first handler's
/// values are more important than the next handlers values, etc.
///
/// Example:
/// If the multiplex log handler was initiated with two handlers like this: `MultiplexLogHandler([handler1, handler2])`.
/// The handlers each have some already set metadata: `handler1` has metadata values for keys `one` and `all`, and `handler2`
/// has values for keys `two` and `all`.
///
/// A query through the multiplex log handler the key `one` naturally returns `handler1`'s value, and a query for `two`
/// naturally returns `handler2`'s value. Querying for the key `all` will return `handler1`'s value, as that handler was indicated
/// "more important" than the second handler. The same rule applies when querying for the `metadata` property of the
/// multiplex log handler - it constructs `Metadata` uniquing values.
public struct MultiplexLogHandler: LogHandler {
private var handlers: [LogHandler]
private var effectiveLogLevel: Logger.Level
/// This metadata provider runs after all metadata providers of the multiplexed handlers.
private var _metadataProvider: Logger.MetadataProvider?
/// Create a `MultiplexLogHandler`.
///
/// - parameters:
/// - handlers: An array of `LogHandler`s, each of which will receive the log messages sent to this `Logger`.
/// The array must not be empty.
public init(_ handlers: [LogHandler]) {
assert(!handlers.isEmpty, "MultiplexLogHandler.handlers MUST NOT be empty")
self.handlers = handlers
self.effectiveLogLevel = handlers.map { $0.logLevel }.min() ?? .trace
}
public init(_ handlers: [LogHandler], metadataProvider: Logger.MetadataProvider?) {
assert(!handlers.isEmpty, "MultiplexLogHandler.handlers MUST NOT be empty")
self.handlers = handlers
self.effectiveLogLevel = handlers.map { $0.logLevel }.min() ?? .trace
self._metadataProvider = metadataProvider
}
public var logLevel: Logger.Level {
get {
return self.effectiveLogLevel
}
set {
self.mutatingForEachHandler { $0.logLevel = newValue }
self.effectiveLogLevel = newValue
}
}
public var metadataProvider: Logger.MetadataProvider? {
get {
if self.handlers.count == 1 {
if let innerHandler = self.handlers.first?.metadataProvider {
if let multiplexHandlerProvider = self._metadataProvider {
return .multiplex([innerHandler, multiplexHandlerProvider])
} else {
return innerHandler
}
} else if let multiplexHandlerProvider = self._metadataProvider {
return multiplexHandlerProvider
} else {
return nil
}
} else {
var providers: [Logger.MetadataProvider] = []
let additionalMetadataProviderCount = (self._metadataProvider != nil ? 1 : 0)
providers.reserveCapacity(self.handlers.count + additionalMetadataProviderCount)
for handler in self.handlers {
if let provider = handler.metadataProvider {
providers.append(provider)
}
}
if let multiplexHandlerProvider = self._metadataProvider {
providers.append(multiplexHandlerProvider)
}
guard !providers.isEmpty else {
return nil
}
return .multiplex(providers)
}
}
set {
self.mutatingForEachHandler { $0.metadataProvider = newValue }
}
}
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
for handler in self.handlers where handler.logLevel <= level {
handler.log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
}
}
public var metadata: Logger.Metadata {
get {
var effective: Logger.Metadata = [:]
// as a rough estimate we assume that the underlying handlers have a similar metadata count,
// and we use the first one's current count to estimate how big of a dictionary we need to allocate:
effective.reserveCapacity(self.handlers.first!.metadata.count) // !-safe, we always have at least one handler
for handler in self.handlers {
effective.merge(handler.metadata, uniquingKeysWith: { _, handlerMetadata in handlerMetadata })
if let provider = handler.metadataProvider {
effective.merge(provider.get(), uniquingKeysWith: { _, provided in provided })
}
}
if let provider = self._metadataProvider {
effective.merge(provider.get(), uniquingKeysWith: { _, provided in provided })
}
return effective
}
set {
self.mutatingForEachHandler { $0.metadata = newValue }
}
}
public subscript(metadataKey metadataKey: Logger.Metadata.Key) -> Logger.Metadata.Value? {
get {
for handler in self.handlers {
if let value = handler[metadataKey: metadataKey] {
return value
}
}
return nil
}
set {
self.mutatingForEachHandler { $0[metadataKey: metadataKey] = newValue }
}
}
private mutating func mutatingForEachHandler(_ mutator: (inout LogHandler) -> Void) {
for index in self.handlers.indices {
mutator(&self.handlers[index])
}
}
}
#if canImport(WASILibc) || os(Android)
internal typealias CFilePointer = OpaquePointer
#else
internal typealias CFilePointer = UnsafeMutablePointer<FILE>
#endif
/// A wrapper to facilitate `print`-ing to stderr and stdio that
/// ensures access to the underlying `FILE` is locked to prevent
/// cross-thread interleaving of output.
internal struct StdioOutputStream: TextOutputStream {
internal let file: CFilePointer
internal let flushMode: FlushMode
internal func write(_ string: String) {
self.contiguousUTF8(string).withContiguousStorageIfAvailable { utf8Bytes in
#if os(Windows)
_lock_file(self.file)
#elseif canImport(WASILibc)
// no file locking on WASI
#else
flockfile(self.file)
#endif
defer {
#if os(Windows)
_unlock_file(self.file)
#elseif canImport(WASILibc)
// no file locking on WASI
#else
funlockfile(self.file)
#endif
}
_ = fwrite(utf8Bytes.baseAddress!, 1, utf8Bytes.count, self.file)
if case .always = self.flushMode {
self.flush()
}
}!
}
/// Flush the underlying stream.
/// This has no effect when using the `.always` flush mode, which is the default
internal func flush() {
_ = fflush(self.file)
}
internal func contiguousUTF8(_ string: String) -> String.UTF8View {
var contiguousString = string
#if compiler(>=5.1)
contiguousString.makeContiguousUTF8()
#else
contiguousString = string + ""
#endif
return contiguousString.utf8
}
internal static let stderr = StdioOutputStream(file: systemStderr, flushMode: .always)
internal static let stdout = StdioOutputStream(file: systemStdout, flushMode: .always)
/// Defines the flushing strategy for the underlying stream.
internal enum FlushMode {
case undefined
case always
}
}
// Prevent name clashes
#if canImport(Darwin)
let systemStderr = Darwin.stderr
let systemStdout = Darwin.stdout
#elseif os(Windows)
let systemStderr = CRT.stderr
let systemStdout = CRT.stdout
#elseif canImport(Glibc)
let systemStderr = Glibc.stderr!
let systemStdout = Glibc.stdout!
#elseif canImport(Musl)
let systemStderr = Musl.stderr!
let systemStdout = Musl.stdout!
#elseif canImport(WASILibc)
let systemStderr = WASILibc.stderr!
let systemStdout = WASILibc.stdout!
#else
#error("Unsupported runtime")
#endif
/// `StreamLogHandler` is a simple implementation of `LogHandler` for directing
/// `Logger` output to either `stderr` or `stdout` via the factory methods.
///
/// Metadata is merged in the following order:
/// 1. Metadata set on the log handler itself is used as the base metadata.
/// 2. The handler's ``metadataProvider`` is invoked, overriding any existing keys.
/// 3. The per-log-statement metadata is merged, overriding any previously set keys.
public struct StreamLogHandler: LogHandler {
#if compiler(>=5.6)
internal typealias _SendableTextOutputStream = TextOutputStream & Sendable
#else
internal typealias _SendableTextOutputStream = TextOutputStream
#endif
/// Factory that makes a `StreamLogHandler` to directs its output to `stdout`
public static func standardOutput(label: String) -> StreamLogHandler {
return StreamLogHandler(label: label, stream: StdioOutputStream.stdout, metadataProvider: LoggingSystem.metadataProvider)
}
/// Factory that makes a `StreamLogHandler` that directs its output to `stdout`
public static func standardOutput(label: String, metadataProvider: Logger.MetadataProvider?) -> StreamLogHandler {
return StreamLogHandler(label: label, stream: StdioOutputStream.stdout, metadataProvider: metadataProvider)
}
/// Factory that makes a `StreamLogHandler` that directs its output to `stderr`
public static func standardError(label: String) -> StreamLogHandler {
return StreamLogHandler(label: label, stream: StdioOutputStream.stderr, metadataProvider: LoggingSystem.metadataProvider)
}
/// Factory that makes a `StreamLogHandler` that direct its output to `stderr`
public static func standardError(label: String, metadataProvider: Logger.MetadataProvider?) -> StreamLogHandler {
return StreamLogHandler(label: label, stream: StdioOutputStream.stderr, metadataProvider: metadataProvider)
}
private let stream: _SendableTextOutputStream
private let label: String
public var logLevel: Logger.Level = .info
public var metadataProvider: Logger.MetadataProvider?
private var prettyMetadata: String?
public var metadata = Logger.Metadata() {
didSet {
self.prettyMetadata = self.prettify(self.metadata)
}
}
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.metadata[metadataKey]
}
set {
self.metadata[metadataKey] = newValue
}
}
// internal for testing only
internal init(label: String, stream: _SendableTextOutputStream) {
self.init(label: label, stream: stream, metadataProvider: LoggingSystem.metadataProvider)
}
// internal for testing only
internal init(label: String, stream: _SendableTextOutputStream, metadataProvider: Logger.MetadataProvider?) {
self.label = label
self.stream = stream
self.metadataProvider = metadataProvider
}
public func log(level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
let effectiveMetadata = StreamLogHandler.prepareMetadata(base: self.metadata, provider: self.metadataProvider, explicit: explicitMetadata)
let prettyMetadata: String?
if let effectiveMetadata = effectiveMetadata {
prettyMetadata = self.prettify(effectiveMetadata)
} else {
prettyMetadata = self.prettyMetadata
}
var stream = self.stream
stream.write("\(self.timestamp()) \(level) \(self.label) :\(prettyMetadata.map { " \($0)" } ?? "") [\(source)] \(message)\n")
}
internal static func prepareMetadata(base: Logger.Metadata, provider: Logger.MetadataProvider?, explicit: Logger.Metadata?) -> Logger.Metadata? {
var metadata = base
let provided = provider?.get() ?? [:]
guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) else {
// all per-log-statement values are empty
return nil
}
if !provided.isEmpty {
metadata.merge(provided, uniquingKeysWith: { _, provided in provided })
}
if let explicit = explicit, !explicit.isEmpty {
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
}
return metadata
}
private func prettify(_ metadata: Logger.Metadata) -> String? {
if metadata.isEmpty {
return nil
} else {
return metadata.lazy.sorted(by: { $0.key < $1.key }).map { "\($0)=\($1)" }.joined(separator: " ")
}
}
private func timestamp() -> String {
var buffer = [Int8](repeating: 0, count: 255)
#if os(Windows)
var timestamp = __time64_t()
_ = _time64(×tamp)
var localTime = tm()
_ = _localtime64_s(&localTime, ×tamp)
_ = strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", &localTime)
#else
var timestamp = time(nil)
guard let localTime = localtime(×tamp) else {
return "<unknown>"
}
strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime)
#endif
return buffer.withUnsafeBufferPointer {
$0.withMemoryRebound(to: CChar.self) {
String(cString: $0.baseAddress!)
}
}
}
}
/// No operation LogHandler, used when no logging is required
public struct SwiftLogNoOpLogHandler: LogHandler {
public init() {}
public init(_: String) {}
@inlinable public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {}
@inlinable public subscript(metadataKey _: String) -> Logger.Metadata.Value? {
get {
return nil
}
set {}
}
@inlinable public var metadata: Logger.Metadata {
get {
return [:]
}
set {}
}
@inlinable public var logLevel: Logger.Level {
get {
return .critical
}
set {}
}
}
extension Logger {
@inlinable
internal static func currentModule(filePath: String = #file) -> String {
let utf8All = filePath.utf8
return filePath.utf8.lastIndex(of: UInt8(ascii: "/")).flatMap { lastSlash -> Substring? in
utf8All[..<lastSlash].lastIndex(of: UInt8(ascii: "/")).map { secondLastSlash -> Substring in
filePath[utf8All.index(after: secondLastSlash) ..< lastSlash]
}
}.map {
String($0)
} ?? "n/a"
}
#if compiler(>=5.3)
@inlinable
internal static func currentModule(fileID: String = #fileID) -> String {
let utf8All = fileID.utf8
if let slashIndex = utf8All.firstIndex(of: UInt8(ascii: "/")) {
return String(fileID[..<slashIndex])
} else {
return "n/a"
}
}
#endif
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9686
extension Logger.MetadataValue: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public init(stringLiteral value: String) {
self = .string(value)
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9686
extension Logger.MetadataValue: CustomStringConvertible {
public var description: String {
switch self {
case .dictionary(let dict):
return dict.mapValues { $0.description }.description
case .array(let list):
return list.map { $0.description }.description
case .string(let str):
return str
case .stringConvertible(let repr):
return repr.description
}
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByStringInterpolation {}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9686
extension Logger.MetadataValue: ExpressibleByDictionaryLiteral {
public typealias Key = String
public typealias Value = Logger.Metadata.Value
public init(dictionaryLiteral elements: (String, Logger.Metadata.Value)...) {
self = .dictionary(.init(uniqueKeysWithValues: elements))
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9686
extension Logger.MetadataValue: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Logger.Metadata.Value
public init(arrayLiteral elements: Logger.Metadata.Value...) {
self = .array(elements)
}
}
// MARK: - Debug only warnings
#if DEBUG
/// Contains state to manage all kinds of "warn only once" warnings which the logging system may want to issue.
private final class WarnOnceBox {
private let lock: Lock = Lock()
private var warnOnceLogHandlerNotSupportedMetadataProviderPerType: [ObjectIdentifier: Bool] = [:]
func warnOnceLogHandlerNotSupportedMetadataProvider<Handler: LogHandler>(type: Handler.Type) -> Bool {
self.lock.withLock {
let id = ObjectIdentifier(type)
if warnOnceLogHandlerNotSupportedMetadataProviderPerType[id] ?? false {
return false // don't warn, it was already warned about
} else {
warnOnceLogHandlerNotSupportedMetadataProviderPerType[id] = true
return true // warn about this handler type, it is the first time we encountered it
}
}
}
}
#endif
// MARK: - Sendable support helpers
#if compiler(>=5.7.0)
extension Logger.MetadataValue: Sendable {} // on 5.7 `stringConvertible`'s value marked as Sendable; but if a value not conforming to Sendable is passed there, a warning is emitted. We are okay with warnings, but on 5.6 for the same situation an error is emitted (!)
#elseif compiler(>=5.6)
extension Logger.MetadataValue: @unchecked Sendable {} // sadly, On 5.6 a missing Sendable conformance causes an 'error' (specifically this is about `stringConvertible`'s value)
#endif
#if compiler(>=5.6)
extension Logger: Sendable {}
extension Logger.Level: Sendable {}
extension Logger.Message: Sendable {}
#endif
|