Add opt-in millisecond precision to StreamLogHandler timestamp (#483)

`StreamLogHandler` timestamps only have second precision, so when
several log lines land in the same second you can't tell what order they
happened in.

This adds an **opt-in** setting for millisecond precision. The default
output doesn't change, since some users parse it.

**Changes**
- Adds `public var timestampPrecision: TimestampPrecision = .seconds` to
`StreamLogHandler`.
- Adds a nested `TimestampPrecision` enum (`@nonexhaustive`, `Sendable`)
with `.seconds` and `.milliseconds`.
- With `.milliseconds`, the timestamp includes a 3-digit millisecond
field:
  - default (`.seconds`): `2021-11-06T18:47:14+0300 info myapp: message`
  - `.milliseconds`: `2021-11-06T18:47:14.123+0300 info myapp: message`
- How each platform reads the time:
  - Darwin, Linux and Android use `clock_gettime(CLOCK_REALTIME)`.
  - Windows uses `_ftime64_s`.
- WASI only has second resolution (`CLOCK_REALTIME` isn't importable
there), so `.milliseconds` always prints `.000`. The doc comments say
so.
- Both new symbols are added to the DocC reference page.

**Tests**
- The default precision is `.seconds`.
- `.milliseconds` produces the expected format (checked with a regex).
- Milliseconds are always zero-padded to 3 digits.
- The existing output-format tests are unchanged and still pass, which
confirms the default format.

Fixes #212
This commit is contained in:
Krishna Permi authored and GitHub committed 2026-11-03 09:56:27 +00:00
1 parent d0f784af9e
commit c44b210eee
3 files changed
+123 -11

No files matched your search

@@ -25,3 +25,8 @@
- ``logLevel``
- ``metadata``
- ``metadataProvider``
### Configuring the timestamp
- ``timestampPrecision``
- ``TimestampPrecision``
+79 -11
View File
@@ -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(&timestamp)
// _ftime64_s gives wall-clock time with millisecond resolution.
var timeBuffer = __timeb64()
_ = _ftime64_s(&timeBuffer)
var localTime = tm()
_ = _localtime64_s(&localTime, &timestamp)
_ = 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(&timestamp) else {
return "<unknown>"
}
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 "<unknown>"
}
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
}
}
@@ -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"