From 8794711429794d1c65ccd5949d47b43d19e99c8d Mon Sep 17 00:00:00 2001 From: David Rothera Date: Mon, 22 Apr 2024 22:50:23 +0100 Subject: [PATCH] Add structured logging as an alternative to stdout printing This fixes #131 and adds a `oslog` handler for logging as an option. Rather than change all logging to use this new endpoint by default I left it as an option for the client to decide as perhaps people could be relying on stdout printing. The new variable is gated around the platforms which support this new structured logging API (iOS 14 and similar). --- Sources/TelemetryClient/LogHandler.swift | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Sources/TelemetryClient/LogHandler.swift b/Sources/TelemetryClient/LogHandler.swift index 43f4857..d6a855a 100644 --- a/Sources/TelemetryClient/LogHandler.swift +++ b/Sources/TelemetryClient/LogHandler.swift @@ -1,4 +1,5 @@ import Foundation +import OSLog public struct LogHandler { public enum LogLevel: Int, CustomStringConvertible { @@ -16,6 +17,17 @@ public struct LogHandler { return "ERROR" } } + + public var osLogLevel: OSLogType { + switch self { + case .debug: + return OSLogType.debug + case .info: + return OSLogType.info + case .error: + return OSLogType.error + } + } } let logLevel: LogLevel @@ -27,6 +39,16 @@ public struct LogHandler { } } + @available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) + public static var oslog = { logLevel in + LogHandler(logLevel: logLevel) { level, message in + Logger( + subsystem: "TelemetryDeck", + category: "LogHandler" + ).log(level: logLevel.osLogLevel, "\(message, privacy: .public)") + } + } + public static var stdout = { logLevel in LogHandler(logLevel: logLevel) { level, message in print("[TelemetryDeck: \(level.description)] \(message)")