diff --git a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json index bad9172..27083d8 100644 --- a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json +++ b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1605, + "instructions" : 1651, "objectAllocCount" : 0 -} +} \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json index aef8c76..27083d8 100644 --- a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json +++ b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode 26.1/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1608, + "instructions" : 1651, "objectAllocCount" : 0 -} +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.debug_log_with_error_log_level_generic.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.debug_log_with_error_log_level_generic.p90.json index 54965d7..2cd2fd1 100644 --- a/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.debug_log_with_error_log_level_generic.p90.json +++ b/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.debug_log_with_error_log_level_generic.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 981, + "instructions" : 984, "objectAllocCount" : 0 -} +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.error_log_with_error_log_level_generic.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.error_log_with_error_log_level_generic.p90.json index 0002f4b..2d0c127 100644 --- a/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.error_log_with_error_log_level_generic.p90.json +++ b/Benchmarks/NoTraits/Thresholds/Xcode 16.4/NoTraits.error_log_with_error_log_level_generic.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1351, + "instructions" : 1368, "objectAllocCount" : 0 -} +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.debug_log_with_error_log_level_generic.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.debug_log_with_error_log_level_generic.p90.json index 5c9bacc..674bde6 100644 --- a/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.debug_log_with_error_log_level_generic.p90.json +++ b/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.debug_log_with_error_log_level_generic.p90.json @@ -1,4 +1,4 @@ { "instructions" : 893, "objectAllocCount" : 0 -} +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.error_log_with_error_log_level_generic.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.error_log_with_error_log_level_generic.p90.json index bad9172..798db07 100644 --- a/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.error_log_with_error_log_level_generic.p90.json +++ b/Benchmarks/NoTraits/Thresholds/Xcode 26.1/NoTraits.error_log_with_error_log_level_generic.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1605, + "instructions" : 1649, "objectAllocCount" : 0 -} +} \ No newline at end of file diff --git a/Sources/InMemoryLogging/InMemoryLogHandler.swift b/Sources/InMemoryLogging/InMemoryLogHandler.swift index 27b2a77..f863489 100644 --- a/Sources/InMemoryLogging/InMemoryLogHandler.swift +++ b/Sources/InMemoryLogging/InMemoryLogHandler.swift @@ -46,6 +46,8 @@ public struct InMemoryLogHandler: LogHandler { public var level: Logger.Level /// The message which was logged. public var message: Logger.Message + /// The error which was logged. + public var error: (any Error)? /// The metadata which was logged. public var metadata: Logger.Metadata @@ -54,18 +56,49 @@ public struct InMemoryLogHandler: LogHandler { self.message = message self.metadata = metadata } + + public init(level: Logger.Level, message: Logger.Message, error: (any Error)?, metadata: Logger.Metadata) { + self.level = level + self.message = message + self.error = error + self.metadata = metadata + } + + public static func == (lhs: InMemoryLogHandler.Entry, rhs: InMemoryLogHandler.Entry) -> Bool { + lhs.level == rhs.level + && lhs.message == rhs.message + && errorsEqual(lhs.error, rhs.error) + && lhs.metadata == rhs.metadata + } + + private static func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): + return true + case let (l?, r?): + return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r)) + default: + return false + } + } } private final class LogStore: @unchecked Sendable { private var _entries: [Entry] = [] private let lock = Lock() - fileprivate func append(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata) { + fileprivate func append( + level: Logger.Level, + message: Logger.Message, + error: (any Error)?, + metadata: Logger.Metadata + ) { self.lock.withLockVoid { self._entries.append( Entry( level: level, message: message, + error: error, metadata: metadata ) ) @@ -100,7 +133,7 @@ public struct InMemoryLogHandler: LogHandler { // ..merge in metadata from this log call, overwriting existing keys mergedMetadata = mergedMetadata.merging(event.metadata ?? [:]) { $1 } - self.logStore.append(level: event.level, message: event.message, metadata: mergedMetadata) + self.logStore.append(level: event.level, message: event.message, error: event.error, metadata: mergedMetadata) } @available(*, deprecated, renamed: "log(event:)") diff --git a/Sources/Logging/Docs.docc/Proposals/SLG-0003.md b/Sources/Logging/Docs.docc/Proposals/SLG-0003.md index 3c4cc70..656ea92 100644 --- a/Sources/Logging/Docs.docc/Proposals/SLG-0003.md +++ b/Sources/Logging/Docs.docc/Proposals/SLG-0003.md @@ -6,7 +6,7 @@ Add standardized way of attaching data from `Error` instances to log entries. - Proposal: SLG-0003 - Author(s): [Samuel Murray](https://github.com/samuelmurray) -- Status: **Ready for Implementation** +- Status: **Approved** - Issue: [apple/swift-log#291](https://github.com/apple/swift-log/issues/291) - Implementation: - [apple/swift-log#425](https://github.com/apple/swift-log/pull/425) diff --git a/Sources/Logging/LogEvent.swift b/Sources/Logging/LogEvent.swift index b22d44e..16a11f0 100644 --- a/Sources/Logging/LogEvent.swift +++ b/Sources/Logging/LogEvent.swift @@ -26,6 +26,9 @@ public struct LogEvent: Sendable { /// The message of this event. public var message: Logger.Message + /// The error associated with this event, if any. + public var error: (any Error)? + /// The metadata associated with this event, if any. public var metadata: Logger.Metadata? { get { self._metadata } @@ -75,9 +78,44 @@ public struct LogEvent: Sendable { file: String, function: String, line: UInt + ) { + self.init( + level: level, + message: message, + error: nil, + metadata: metadata, + source: source, + file: file, + function: function, + line: line + ) + } + + /// Creates a new log event. + /// + /// - Parameters: + /// - level: The log level of this event. + /// - message: The message of this event. + /// - error: The error associated with this event, if any. + /// - metadata: The metadata associated with this event, if any. + /// - source: The source where this log event originated. When `nil`, ``source`` is derived lazily + /// from ``file`` on first access so handlers that never read it pay no allocation cost. + /// - file: The file this log event originates from. + /// - function: The function this log event originates from. + /// - line: The line this log event originates from. + public init( + level: Logger.Level, + message: Logger.Message, + error: (any Error)?, + metadata: Logger.Metadata?, + source: String?, + file: String, + function: String, + line: UInt ) { self.level = level self.message = message + self.error = error self._metadata = metadata self._source = source self.file = file diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index 43e848d..0c51512 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -97,6 +97,127 @@ public struct Logger { } extension Logger { + /// Log a message using the log level and source that you provide. + /// + /// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library + /// logs the message, otherwise nothing will happen. + /// + /// NOTE: This method adds a constant overhead over calling level-specific methods. + /// + /// - parameters: + /// - level: The severity level of the `message`. + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if MaxLogLevelDebug || MaxLogLevelInfo || MaxLogLevelNotice || MaxLogLevelWarning || MaxLogLevelError || MaxLogLevelCritical || MaxLogLevelNone + // A constant overhead is added for dynamic log level calls if one of the traits is enabled. + // This allows picking the necessary implementation with compiled out body in runtime. + switch level { + case .trace: + self.trace( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + case .debug: + self.debug( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + case .info: + self.info( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + case .notice: + self.notice( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + case .warning: + self.warning( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + case .error: + self.error( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + case .critical: + self.critical( + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + } + #else + // If no logs are excluded in the compile time, we can avoid checking the log level that extra time and go log it. + self._log( + level: level, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message using the log level and source that you provide. /// /// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library @@ -126,37 +247,16 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if MaxLogLevelDebug || MaxLogLevelInfo || MaxLogLevelNotice || MaxLogLevelWarning || MaxLogLevelError || MaxLogLevelCritical || MaxLogLevelNone - // A constant overhead is added for dynamic log level calls if one of the traits is enabled. - // This allows picking the necessary implementation with compiled out body in runtime. - switch level { - case .trace: - self.trace(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - case .debug: - self.debug(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - case .info: - self.info(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - case .notice: - self.notice(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - case .warning: - self.warning(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - case .error: - self.error(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - case .critical: - self.critical(message(), metadata: metadata(), source: source(), file: file, function: function, line: line) - } - #else - // If no logs are excluded in the compile time, we can avoid checking the log level that extra time and go log it. - self._log( + self.log( level: level, message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message using the log level and source that you provide. @@ -180,6 +280,7 @@ extension Logger { package func _log( level: Logger.Level, _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -191,6 +292,7 @@ extension Logger { event: LogEvent( level: level, message: message(), + error: error(), metadata: metadata(), source: source(), file: file, @@ -206,6 +308,8 @@ extension Logger { /// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library /// logs the message, otherwise nothing will happen. /// + /// NOTE: This method adds a constant overhead over calling level-specific methods. + /// /// - parameters: /// - level: The log level to log the `message`. /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. @@ -259,6 +363,47 @@ extension Logger { } extension Logger { + /// Log a message at the 'trace' log level with the source that you provide. + /// + /// If ``Level/trace`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 trace( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelDebug && !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone + self._log( + level: .trace, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'trace' log level with the source that you provide. /// /// If ``Level/trace`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -284,17 +429,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelDebug && !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone - self._log( - level: .trace, + self.trace( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'trace' log level. @@ -322,6 +465,47 @@ extension Logger { self.trace(message(), metadata: metadata(), source: nil, file: file, function: function, line: line) } + /// Log a message at the 'debug' log level with the source that you provide. + /// + /// If ``Level/debug`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 debug( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone + self._log( + level: .debug, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'debug' log level with the source that you provide. /// /// If ``Level/debug`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -347,17 +531,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone - self._log( - level: .debug, + self.debug( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'debug' log level. @@ -385,6 +567,47 @@ extension Logger { self.debug(message(), metadata: metadata(), source: nil, file: file, function: function, line: line) } + /// Log a message at the 'info' log level with the source that you provide. + /// + /// If ``Level/info`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 info( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone + self._log( + level: .info, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'info' log level with the source that you provide. /// /// If ``Level/info`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -410,17 +633,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone - self._log( - level: .info, + self.info( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'info' log level. @@ -448,6 +669,47 @@ extension Logger { self.info(message(), metadata: metadata(), source: nil, file: file, function: function, line: line) } + /// Log a message at the 'notice' log level with the source that you provide. + /// + /// If ``Level/notice`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 notice( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone + self._log( + level: .notice, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'notice' log level with the source that you provide. /// /// If ``Level/notice`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -473,17 +735,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone - self._log( - level: .notice, + self.notice( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'notice' log level. @@ -511,6 +771,47 @@ extension Logger { self.notice(message(), metadata: metadata(), source: nil, file: file, function: function, line: line) } + /// Log a message at the 'warning' log level with the source that you provide. + /// + /// If ``Level/warning`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 warning( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone + self._log( + level: .warning, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'warning' log level with the source that you provide. /// /// If ``Level/warning`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -536,17 +837,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone - self._log( - level: .warning, + self.warning( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'warning' log level. @@ -574,6 +873,47 @@ extension Logger { self.warning(message(), metadata: metadata(), source: nil, file: file, function: function, line: line) } + /// Log a message at the 'error' log level with the source that you provide. + /// + /// If ``Level/error`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 error( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelCritical && !MaxLogLevelNone + self._log( + level: .error, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'error' log level with the source that you provide. /// /// If ``Level/error`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -599,17 +939,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelCritical && !MaxLogLevelNone - self._log( - level: .error, + self.error( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'error' log level. @@ -637,6 +975,47 @@ extension Logger { self.error(message(), metadata: metadata(), source: nil, file: file, function: function, line: line) } + /// Log a message at the 'critical' log level with the source that you provide. + /// + /// If ``Level/critical`` is at least as severe as this logger's ``logLevel`` the system logs the message; + /// otherwise nothing will happen. + /// + /// - parameters: + /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. + /// - error: An `Error` related to the event. + /// - metadata: One-off metadata to attach to this log message. + /// - source: The source this log message originates from. The value defaults + /// to the module that emits the log message. + /// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it + /// defaults to `#fileID`. + /// - 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 critical( + _ message: @autoclosure () -> Logger.Message, + error: @autoclosure () -> (any Error)? = nil, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, + function: String = #function, + line: UInt = #line + ) { + #if !MaxLogLevelNone + self._log( + level: .critical, + message(), + error: error(), + metadata: metadata(), + source: source(), + file: file, + function: function, + line: line + ) + #endif + } + /// Log a message at the 'critical' log level with the source that you provide. /// /// If ``Level/critical`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -662,17 +1041,15 @@ extension Logger { function: String = #function, line: UInt = #line ) { - #if !MaxLogLevelNone - self._log( - level: .critical, + self.critical( message(), + error: nil, metadata: metadata(), source: source(), file: file, function: function, line: line ) - #endif } /// Log a message at the 'critical' log level. @@ -1684,7 +2061,8 @@ public struct StreamLogHandler: LogHandler { let effectiveMetadata = StreamLogHandler.prepareMetadata( base: self.metadata, provider: self.metadataProvider, - explicit: event.metadata + explicit: event.metadata, + error: event.error, ) let prettyMetadata: String? @@ -1726,13 +2104,14 @@ public struct StreamLogHandler: LogHandler { internal static func prepareMetadata( base: Logger.Metadata, provider: Logger.MetadataProvider?, - explicit: Logger.Metadata? + explicit: Logger.Metadata?, + error: (any Error)?, ) -> Logger.Metadata? { var metadata = base let provided = provider?.get() ?? [:] - guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) else { + guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) || error != nil else { // all per-log-statement values are empty return nil } @@ -1745,6 +2124,11 @@ public struct StreamLogHandler: LogHandler { metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit }) } + if let error { + metadata["error.message"] = "\(error)" + metadata["error.type"] = "\(String(reflecting: type(of: error)))" + } + return metadata } diff --git a/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift b/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift index fd600cc..cde34c5 100644 --- a/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift +++ b/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift @@ -69,6 +69,53 @@ struct InMemoryLogHandlerTests { ) } + @Test + func errorEquality() throws { + let (logHandler, logger) = self.makeTestLogger() + logger.info("hello", error: TestError.first) + let entry = try #require(logHandler.entries.first) + + #expect( + entry + == InMemoryLogHandler.Entry( + level: .info, + message: "hello", + error: TestError.first, + metadata: [:], + ) + ) + + #expect( + entry + != InMemoryLogHandler.Entry( + level: .info, + message: "hello", + error: nil, + metadata: [:], + ) + ) + + #expect( + entry + != InMemoryLogHandler.Entry( + level: .info, + message: "hello", + error: TestError.second, + metadata: [:] + ) + ) + + #expect( + entry + != InMemoryLogHandler.Entry( + level: .info, + message: "hello", + error: Nested.TestError.first, + metadata: [:] + ) + ) + } + @Test func clear() { let (logHandler, logger) = self.makeTestLogger() @@ -95,4 +142,15 @@ struct InMemoryLogHandlerTests { ) return (logHandler, logger) } + + enum TestError: Error { + case first + case second + } + + struct Nested { + enum TestError: Error { + case first + } + } } diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index 80d661e..57f51be 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -387,6 +387,7 @@ struct LoggingTest { enum TestError: Error { case boom + case withMessage(String) } @Test func dictionaryMetadata() { @@ -515,6 +516,7 @@ struct LoggingTest { logger.debug(self.dontEvaluateThisString()) logger.info(self.dontEvaluateThisString()) logger.warning(self.dontEvaluateThisString()) + logger.warning(self.dontEvaluateThisString(), error: TestError.withMessage("\(self.dontEvaluateThisString())")) logger.log(level: .warning, self.dontEvaluateThisString()) } @@ -567,6 +569,19 @@ struct LoggingTest { #expect(logger2.handler is CustomHandler, "expected custom log handler") } + @Test func errorParameter() { + let testLogging = TestLogging() + + let logger = Logger( + label: "\(#function)", + factory: { + testLogging.make(label: $0) + } + ) + logger.log(level: .info, "hello world!", error: TestError.boom) + testLogging.history.assertExist(level: .info, message: "hello world!", error: TestError.boom) + } + @Test func allLogLevelsExceptCriticalCanBeBlocked() { let testLogging = TestLogging() @@ -623,7 +638,48 @@ struct LoggingTest { testLogging.history.assertExist(level: .critical, message: "yes: critical") } - @Test func allLogLevelByFunctionRefWithSource() { + @Test func allLogLevelByFunctionRefWithSourceAndError() { + let testLogging = TestLogging() + + var logger = Logger( + label: "\(#function)", + factory: { + testLogging.make(label: $0) + } + ) + logger.logLevel = .trace + + let trace = logger.trace(_:error:metadata:source:file:function:line:) + let debug = logger.debug(_:error:metadata:source:file:function:line:) + let info = logger.info(_:error:metadata:source:file:function:line:) + let notice = logger.notice(_:error:metadata:source:file:function:line:) + let warning = logger.warning(_:error:metadata:source:file:function:line:) + let error = logger.error(_:error:metadata:source:file:function:line:) + let critical = logger.critical(_:error:metadata:source:file:function:line:) + + trace("yes: trace", TestError.boom, [:], "foo", #file, #function, #line) + debug("yes: debug", TestError.boom, [:], "foo", #file, #function, #line) + info("yes: info", TestError.boom, [:], "foo", #file, #function, #line) + notice("yes: notice", TestError.boom, [:], "foo", #file, #function, #line) + warning("yes: warning", TestError.boom, [:], "foo", #file, #function, #line) + error("yes: error", TestError.boom, [:], "foo", #file, #function, #line) + critical("yes: critical", TestError.boom, [:], "foo", #file, #function, #line) + + testLogging.history.assertExist(level: .trace, message: "yes: trace", error: TestError.boom, source: "foo") + testLogging.history.assertExist(level: .debug, message: "yes: debug", error: TestError.boom, source: "foo") + testLogging.history.assertExist(level: .info, message: "yes: info", error: TestError.boom, source: "foo") + testLogging.history.assertExist(level: .notice, message: "yes: notice", error: TestError.boom, source: "foo") + testLogging.history.assertExist(level: .warning, message: "yes: warning", error: TestError.boom, source: "foo") + testLogging.history.assertExist(level: .error, message: "yes: error", error: TestError.boom, source: "foo") + testLogging.history.assertExist( + level: .critical, + message: "yes: critical", + error: TestError.boom, + source: "foo" + ) + } + + @Test func allLogLevelByFunctionRefWithSourceWithoutError() { let testLogging = TestLogging() var logger = Logger( @@ -659,7 +715,7 @@ struct LoggingTest { testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "foo") } - @Test func allLogLevelByFunctionRefWithoutSource() { + @Test func allLogLevelByFunctionRefWithoutSourceOrError() { let testLogging = TestLogging() var logger = Logger( diff --git a/Tests/LoggingTests/TestLogger.swift b/Tests/LoggingTests/TestLogger.swift index 8aa15bd..261e2d3 100644 --- a/Tests/LoggingTests/TestLogger.swift +++ b/Tests/LoggingTests/TestLogger.swift @@ -90,13 +90,20 @@ internal struct TestLogHandler: LogHandler { self.logger.log( level: event.level, event.message, + error: event.error, metadata: metadata, source: event.source, file: event.file, function: event.function, line: event.line ) - self.recorder.record(level: event.level, metadata: metadata, message: event.message, source: event.source) + self.recorder.record( + level: event.level, + metadata: metadata, + message: event.message, + error: event.error, + source: event.source + ) } private var _logLevel: Logger.Level? @@ -167,10 +174,16 @@ internal class Recorder: History { private let lock = NSLock() private var _entries = [LogEntry]() - func record(level: Logger.Level, metadata: Logger.Metadata?, message: Logger.Message, source: String) { + func record( + level: Logger.Level, + metadata: Logger.Metadata?, + message: Logger.Message, + error: (any Error)? = nil, + source: String + ) { self.lock.withLock { self._entries.append( - LogEntry(level: level, metadata: metadata, message: message.description, source: source) + LogEntry(level: level, metadata: metadata, message: message.description, error: error, source: source) ) } } @@ -179,6 +192,7 @@ internal class Recorder: History { level: Logger.Level, metadata: Logger.Metadata?, message: Logger.Message, + error: (any Error)? = nil, source: String, file: String, function: String, @@ -190,6 +204,7 @@ internal class Recorder: History { level: level, metadata: metadata, message: message.description, + error: error, source: source, file: file, function: function, @@ -240,6 +255,7 @@ internal struct LogEntry { let level: Logger.Level let metadata: Logger.Metadata? let message: String + let error: (any Error)? let source: String let file: String let function: String @@ -249,6 +265,7 @@ internal struct LogEntry { level: Logger.Level, metadata: Logger.Metadata?, message: String, + error: (any Error)?, source: String, file: String = "", function: String = "", @@ -257,6 +274,7 @@ internal struct LogEntry { self.level = level self.metadata = metadata self.message = message + self.error = error self.source = source self.file = file self.function = function @@ -268,6 +286,7 @@ extension History { func assertExist( level: Logger.Level, message: String, + error: (any Error)? = nil, metadata: Logger.Metadata? = nil, source: String? = nil, file: String = #filePath, @@ -276,10 +295,10 @@ extension History { column: Int = #column ) { let source = source ?? Logger.currentModule(fileID: "\(fileID)") - let entry = self.find(level: level, message: message, metadata: metadata, source: source) + let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source) #expect( entry != nil, - "entry not found: \(level), \(source), \(String(describing: metadata)), \(message)", + "entry not found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))", sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column) ) } @@ -287,6 +306,7 @@ extension History { func assertNotExist( level: Logger.Level, message: String, + error: (any Error)? = nil, metadata: Logger.Metadata? = nil, source: String? = nil, file: String = #filePath, @@ -295,15 +315,21 @@ extension History { column: Int = #column ) { let source = source ?? Logger.currentModule(fileID: "\(fileID)") - let entry = self.find(level: level, message: message, metadata: metadata, source: source) + let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source) #expect( entry == nil, - "entry was found: \(level), \(source), \(String(describing: metadata)), \(message)", + "entry was found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))", sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column) ) } - func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? { + func find( + level: Logger.Level, + message: String, + error: (any Error)? = nil, + metadata: Logger.Metadata? = nil, + source: String + ) -> LogEntry? { self.entries.first { entry in if entry.level != level { return false @@ -311,6 +337,9 @@ extension History { if entry.message != message { return false } + if !errorsEqual(error, entry.error) { + return false + } if let lhs = entry.metadata, let rhs = metadata { if lhs.count != rhs.count { return false @@ -337,6 +366,17 @@ extension History { return true } } + + private func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): + return true + case let (l?, r?): + return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r)) + default: + return false + } + } } /// MDC stands for Mapped Diagnostic Context diff --git a/Tests/LoggingTests/TestSendable.swift b/Tests/LoggingTests/TestSendable.swift index a6b4fa2..4ed4704 100644 --- a/Tests/LoggingTests/TestSendable.swift +++ b/Tests/LoggingTests/TestSendable.swift @@ -29,12 +29,14 @@ struct SendableTest { let message1 = Logger.Message(stringLiteral: "critical 1") let message2 = Logger.Message(stringLiteral: "critical 2") let metadata: Logger.Metadata = ["key": "value"] + let error = TestError() let task = Task.detached { logger.info("info") logger.critical(message1) logger.critical(message2) logger.warning(.init(stringLiteral: "warning"), metadata: metadata) + logger.warning("error", error: error) } await task.value @@ -42,5 +44,8 @@ struct SendableTest { testLogging.history.assertExist(level: .critical, message: "critical 1", metadata: [:]) testLogging.history.assertExist(level: .critical, message: "critical 2", metadata: [:]) testLogging.history.assertExist(level: .warning, message: "warning", metadata: metadata) + testLogging.history.assertExist(level: .warning, message: "error", error: error) } + + final class TestError: Error {} }