|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import Foundation |
| 6 | +#if canImport(MozillaRustComponents) |
| 7 | + import MozillaRustComponents |
| 8 | +#endif |
| 9 | + |
| 10 | +/// The level of a log message |
| 11 | +public enum LogLevel: Int32 { |
| 12 | + /// The log message in question is verbose information which |
| 13 | + /// may contain user PII. |
| 14 | + case trace = 2 |
| 15 | + /// The log message in question is verbose information, |
| 16 | + /// but should contain no PII. |
| 17 | + case debug |
| 18 | + /// The log message is informational |
| 19 | + case info |
| 20 | + /// The log message is a warning |
| 21 | + case warn |
| 22 | + /// The log message indicates an error. |
| 23 | + case error |
| 24 | + |
| 25 | + init(safeRawValue value: Int32) { |
| 26 | + if let result = LogLevel(rawValue: value) { |
| 27 | + self = result |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + if value < LogLevel.trace.rawValue { |
| 32 | + self = .trace |
| 33 | + } else { |
| 34 | + self = .error |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/// An enum representing a maximum log level. It is used with |
| 40 | +/// `RustLog.shared.setLevelFilter`. |
| 41 | +/// |
| 42 | +/// This is roughly equivalent to LogLevel, however contains |
| 43 | +/// `Off`, for filtering all logging. |
| 44 | +public enum LogLevelFilter: Int32 { |
| 45 | + /// Disable all logging |
| 46 | + case off |
| 47 | + /// Only allow `error` logs. |
| 48 | + case error |
| 49 | + /// Allow `warn` and `error` logs. |
| 50 | + case warn |
| 51 | + /// Allow `warn`, `error`, and `info` logs. |
| 52 | + case info |
| 53 | + /// Allow `warn`, `error`, `info`, and `debug` logs. The default. |
| 54 | + case debug |
| 55 | + /// Allow all logs, including those that may contain PII. |
| 56 | + case trace |
| 57 | +} |
| 58 | + |
| 59 | +/// The type of the log callback. You can provide a value of this type to |
| 60 | +/// `RustLog.shared.enable` or `RustLog.shared.tryEnable`, and it will be called for |
| 61 | +/// all log messages emitted by Rust code. |
| 62 | +/// |
| 63 | +/// The first argument is the level of the log. The maximum value of this can |
| 64 | +/// be provided using the `RustLog.shared.setLevelFilter` method. |
| 65 | +/// |
| 66 | +/// The second argument is the tag, which is typically a rust module path |
| 67 | +/// string. It might be nil in some cases that aren't documented by the |
| 68 | +/// underlying rust log crate. |
| 69 | +/// |
| 70 | +/// The last argument is the log message. It will not be nil. |
| 71 | +/// |
| 72 | +/// This callback should return `true` to indicate everything is fine, and |
| 73 | +/// false if we should disable the logger. You cannot call `disable()` |
| 74 | +/// from inside the callback (it's protected by a dispatch queue you're |
| 75 | +/// already running on). |
| 76 | +public typealias LogCallback = (_ level: LogLevel, _ tag: String?, _ message: String) -> Bool |
| 77 | + |
| 78 | +/// The public interface to Rust's logger. |
| 79 | +/// |
| 80 | +/// This is a singleton, and should be used via the |
| 81 | +/// `shared` static member. |
| 82 | +public class RustLog { |
| 83 | + fileprivate let state = RustLogState() |
| 84 | + fileprivate let queue = DispatchQueue(label: "com.mozilla.appservices.rust-log") |
| 85 | + /// The singleton instance of RustLog |
| 86 | + public static let shared = RustLog() |
| 87 | + |
| 88 | + private init() {} |
| 89 | + |
| 90 | + /// True if the logger currently has a bound callback. |
| 91 | + public var isEnabled: Bool { |
| 92 | + return queue.sync { state.isEnabled } |
| 93 | + } |
| 94 | + |
| 95 | + /// Set the current log callback. |
| 96 | + /// |
| 97 | + /// Note that by default, after enabling the level filter |
| 98 | + /// will be at the `debug` level. If you want to increase or decrease it, |
| 99 | + /// you may use `setLevelFilter` |
| 100 | + /// |
| 101 | + /// |
| 102 | + /// See alse `tryEnable`. |
| 103 | + /// |
| 104 | + /// Throws: |
| 105 | + /// |
| 106 | + /// - `RustLogError.alreadyEnabled`: If we're already enabled. Explicitly disable first. |
| 107 | + /// |
| 108 | + /// - `RustLogError.unexpectedError`: If the rust code panics. This shouldn't happen, |
| 109 | + /// but if it does, we would appreciate reports from telemetry or similar |
| 110 | + public func enable(_ callback: @escaping LogCallback) throws { |
| 111 | + try queue.sync { |
| 112 | + try state.enable(callback) |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /// Set the level filter (the maximum log level) of the logger. |
| 117 | + /// |
| 118 | + /// Throws: |
| 119 | + /// - `RustLogError.unexpectedError`: If the rust code panics. This shouldn't happen, |
| 120 | + /// but if it does, we would appreciate reports from telemetry or similar |
| 121 | + public func setLevelFilter(filter: LogLevelFilter) throws { |
| 122 | + // Note: Doesn't need to synchronize. |
| 123 | + try rustCall { error in |
| 124 | + rc_log_adapter_set_max_level(filter.rawValue, error) |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + /// Disable the previously set logger. This also sets the level filter to `.off`. |
| 129 | + /// |
| 130 | + /// Does nothing if the logger is disabled |
| 131 | + public func disable() { |
| 132 | + queue.sync { |
| 133 | + state.disable() |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /// Enable the logger if possible. |
| 138 | + /// |
| 139 | + /// Returns false in the cases where `enable` would throw, true otherwise. |
| 140 | + /// |
| 141 | + /// If it would throw due to a panic, it also writes some information about |
| 142 | + /// the panic to the provided callback |
| 143 | + public func tryEnable(_ callback: @escaping LogCallback) -> Bool { |
| 144 | + return queue.sync { |
| 145 | + state.tryEnable(callback) |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + /// Log a test message at `.info` severity. |
| 150 | + public func logTestMessage(message: String) { |
| 151 | + rc_log_adapter_test__log_msg(message) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +/// The type of errors reported by RustLog. These either indicate bugs |
| 156 | +/// in our logging code (as in `UnexpectedError`), or usage errors |
| 157 | +/// (as in `AlreadyEnabled`) |
| 158 | +public enum RustLogError: Error { |
| 159 | + /// This generally means a panic occurred, or something went very wrong. |
| 160 | + /// We would appreciate bug reports about when these appear in the wild, if they do. |
| 161 | + case unexpectedError(message: String) |
| 162 | + |
| 163 | + /// Error indicating that the log adapter cannot be enabled |
| 164 | + /// because it is already enabled. |
| 165 | + /// |
| 166 | + /// This is a usage error, either `disable` it first, or |
| 167 | + /// use `RustLog.shared.tryEnable` |
| 168 | + case alreadyEnabled |
| 169 | +} |
| 170 | + |
| 171 | +@discardableResult |
| 172 | +private func rustCall<T>(_ callback: (UnsafeMutablePointer<RcLogError>) throws -> T) throws -> T { |
| 173 | + var err = RcLogError(code: 0, message: nil) |
| 174 | + let result = try callback(&err) |
| 175 | + if err.code != 0 { |
| 176 | + let message: String |
| 177 | + if let messageP = err.message { |
| 178 | + defer { rc_log_adapter_destroy_string(messageP) } |
| 179 | + message = String(cString: messageP) |
| 180 | + } else { |
| 181 | + message = "Bug: No message provided with code \(err.code)!" |
| 182 | + } |
| 183 | + throw RustLogError.unexpectedError(message: message) |
| 184 | + } |
| 185 | + return result |
| 186 | +} |
| 187 | + |
| 188 | +// This is the function actually passed to Rust. |
| 189 | +private func logCallbackFunc(level: Int32, optTagP: UnsafePointer<CChar>?, msgP: UnsafePointer<CChar>) { |
| 190 | + guard let callback = RustLog.shared.state.callback else { |
| 191 | + return |
| 192 | + } |
| 193 | + let msg = String(cString: msgP) |
| 194 | + // Probably a better way to do this... |
| 195 | + let tag: String? |
| 196 | + if let optTagP = optTagP { |
| 197 | + tag = String(cString: optTagP) |
| 198 | + } else { |
| 199 | + tag = nil |
| 200 | + } |
| 201 | + RustLog.shared.queue.async { |
| 202 | + if !callback(LogLevel(safeRawValue: level), tag, msg) { |
| 203 | + RustLog.shared.state.disable() |
| 204 | + } |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +// This implements everything, but without synchronization. It needs to be |
| 209 | +// guarded by a queue, which is done by the RustLog class. |
| 210 | +private class RustLogState { |
| 211 | + var adapter: OpaquePointer? |
| 212 | + var callback: LogCallback? |
| 213 | + |
| 214 | + var isEnabled: Bool { return adapter != nil } |
| 215 | + |
| 216 | + func enable(_ callback: @escaping LogCallback) throws { |
| 217 | + if isEnabled { |
| 218 | + throw RustLogError.alreadyEnabled |
| 219 | + } |
| 220 | + assert(self.callback == nil) |
| 221 | + self.callback = callback |
| 222 | + adapter = try rustCall { error in |
| 223 | + rc_log_adapter_create(logCallbackFunc, error) |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + func disable() { |
| 228 | + guard let adapter = adapter else { |
| 229 | + return |
| 230 | + } |
| 231 | + self.adapter = nil |
| 232 | + callback = nil |
| 233 | + rc_log_adapter_destroy(adapter) |
| 234 | + } |
| 235 | + |
| 236 | + func tryEnable(_ callback: @escaping LogCallback) -> Bool { |
| 237 | + if isEnabled { |
| 238 | + return false |
| 239 | + } |
| 240 | + do { |
| 241 | + try enable(callback) |
| 242 | + return true |
| 243 | + } catch { |
| 244 | + _ = callback(.error, |
| 245 | + "RustLog.swift", |
| 246 | + "RustLog.enable failed: \(error)") |
| 247 | + return false |
| 248 | + } |
| 249 | + } |
| 250 | +} |
0 commit comments