diff --git a/Sources/Logging/Docs.docc/Reference/StreamLogHandler.md b/Sources/Logging/Docs.docc/Reference/StreamLogHandler.md index ee70ae1..0795af3 100644 --- a/Sources/Logging/Docs.docc/Reference/StreamLogHandler.md +++ b/Sources/Logging/Docs.docc/Reference/StreamLogHandler.md @@ -25,3 +25,8 @@ - ``logLevel`` - ``metadata`` - ``metadataProvider`` + +### Configuring the timestamp + +- ``timestampPrecision`` +- ``TimestampPrecision`` diff --git a/Sources/Logging/Handlers/StreamLogHandler.swift b/Sources/Logging/Handlers/StreamLogHandler.swift index 31a4e6d..3ab8915 100644 --- a/Sources/Logging/Handlers/StreamLogHandler.swift +++ b/Sources/Logging/Handlers/StreamLogHandler.swift @@ -80,6 +80,19 @@ public struct StreamLogHandler: LogHandler { /// The metadata provider. public var metadataProvider: Logger.MetadataProvider? + /// The precision of the timestamp written at the start of each log line. + /// + /// Defaults to ``TimestampPrecision/seconds``, which keeps the output format + /// that `StreamLogHandler` has always used, for example `2025-06-01T14:03:07+0000`. + /// Some tools parse this output, so the extra precision is opt-in rather than the default. + /// + /// Set it to ``TimestampPrecision/milliseconds`` to include milliseconds, + /// for example `2025-06-01T14:03:07.042+0000`. + /// + /// > Note: On WASI the wall clock is only read with second precision, so + /// > ``TimestampPrecision/milliseconds`` always prints `.000` there. + public var timestampPrecision: TimestampPrecision = .seconds + private var prettyMetadata: String? /// Get or set the entire metadata storage as a dictionary. public var metadata = Logger.Metadata() { @@ -144,7 +157,7 @@ public struct StreamLogHandler: LogHandler { var stream = self.stream stream.write( - "\(self.timestamp()) \(event.level)\(self.label.isEmpty ? "" : " ")\(self.label):\(prettyMetadata.map { " \($0)" } ?? "") [\(event.source)] \(event.message)\n" + "\(self.timestamp(precision: self.timestampPrecision)) \(event.level)\(self.label.isEmpty ? "" : " ")\(self.label):\(prettyMetadata.map { " \($0)" } ?? "") [\(event.source)] \(event.message)\n" ) } @@ -210,28 +223,83 @@ public struct StreamLogHandler: LogHandler { } } - private func timestamp() -> String { + private func timestamp(precision: TimestampPrecision) -> String { var buffer = [Int8](repeating: 0, count: 255) + var tzBuffer = [Int8](repeating: 0, count: 16) + let milliseconds: Int #if os(Windows) - var timestamp = __time64_t() - _ = _time64(×tamp) - + // _ftime64_s gives wall-clock time with millisecond resolution. + var timeBuffer = __timeb64() + _ = _ftime64_s(&timeBuffer) var localTime = tm() - _ = _localtime64_s(&localTime, ×tamp) - - _ = strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", &localTime) - #else + _ = _localtime64_s(&localTime, &timeBuffer.time) + _ = strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S", &localTime) + _ = strftime(&tzBuffer, tzBuffer.count, "%z", &localTime) + milliseconds = Int(timeBuffer.millitm) + #elseif canImport(WASILibc) + // CLOCK_REALTIME isn't importable on WASI (it's a pointer-to-struct macro), + // so fall back to time(nil), which only has second resolution. var timestamp = time(nil) guard let localTime = localtime(×tamp) else { return "" } - strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime) + strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S", localTime) + strftime(&tzBuffer, tzBuffer.count, "%z", localTime) + milliseconds = 0 + #else + var timeSpec = timespec() + clock_gettime(CLOCK_REALTIME, &timeSpec) + guard let localTime = localtime(&timeSpec.tv_sec) else { + return "" + } + strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S", localTime) + strftime(&tzBuffer, tzBuffer.count, "%z", localTime) + milliseconds = Int(timeSpec.tv_nsec) / 1_000_000 #endif - return buffer.withUnsafeBufferPointer { + let dateTime = buffer.withUnsafeBufferPointer { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } } + let timeZone = tzBuffer.withUnsafeBufferPointer { + $0.withMemoryRebound(to: CChar.self) { + String(cString: $0.baseAddress!) + } + } + switch precision { + case .seconds: + return "\(dateTime)\(timeZone)" + case .milliseconds: + return "\(dateTime).\(Self.zeroPadded(milliseconds))\(timeZone)" + } + } + + /// Pads a millisecond value to three digits without pulling in Foundation. + internal static func zeroPadded(_ milliseconds: Int) -> String { + if milliseconds < 10 { + return "00\(milliseconds)" + } else if milliseconds < 100 { + return "0\(milliseconds)" + } else { + return "\(milliseconds)" + } + } +} + +extension StreamLogHandler { + /// The precision of the timestamp that a ``StreamLogHandler`` writes at the start of each log line. + @nonexhaustive + public enum TimestampPrecision: Sendable, Hashable { + /// Whole seconds, for example `2025-06-01T14:03:07+0000`. + /// + /// This is the default, and matches the format `StreamLogHandler` has always produced. + case seconds + + /// Milliseconds, for example `2025-06-01T14:03:07.042+0000`. + /// + /// > Note: On WASI the wall clock only has second resolution, so the + /// > millisecond field is always `.000`. + case milliseconds } } diff --git a/Tests/LoggingTests/StreamLogHandlerTest.swift b/Tests/LoggingTests/StreamLogHandlerTest.swift index 2302253..d41fa95 100644 --- a/Tests/LoggingTests/StreamLogHandlerTest.swift +++ b/Tests/LoggingTests/StreamLogHandlerTest.swift @@ -85,6 +85,45 @@ struct StreamLogHandlerTest { #expect(interceptStream.strings.count == 1) } + @Test func streamLogHandlerTimestampPrecisionDefaultsToSeconds() { + let handler = StreamLogHandler(label: "testLabel", stream: InterceptStream()) + #expect(handler.timestampPrecision == .seconds) + } + + @Test func streamLogHandlerOutputFormatWithMillisecondPrecision() { + let interceptStream = InterceptStream() + let label = "testLabel" + let source = "testSource" + let log = Logger( + label: label, + factory: { + var handler = StreamLogHandler(label: $0, stream: interceptStream) + handler.timestampPrecision = .milliseconds + return handler + } + ) + + let testString = "my message is better than yours" + log.critical("\(testString)", source: source) + + let pattern = + "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label):\\s\\[\(source)\\]\\s\(testString)$" + + let messageSucceeded = + interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range( + of: pattern, + options: .regularExpression + ) != nil + + #expect(messageSucceeded) + #expect(interceptStream.strings.count == 1) + } + + @Test(arguments: [(0, "000"), (7, "007"), (42, "042"), (999, "999")]) + func streamLogHandlerMillisecondsAreZeroPadded(milliseconds: Int, expected: String) { + #expect(StreamLogHandler.zeroPadded(milliseconds) == expected) + } + @Test func streamLogHandlerOutputFormatWithEmptyLabel() { let interceptStream = InterceptStream() let source = "testSource"