-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathLogger.swift
More file actions
315 lines (268 loc) · 8.84 KB
/
Copy pathLogger.swift
File metadata and controls
315 lines (268 loc) · 8.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* Copyright 2025 LiveKit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import OSLog
internal import LiveKitWebRTC
internal import LiveKitUniFFI
// MARK: - Logger
public typealias ScopedMetadata = CustomStringConvertible
public typealias ScopedMetadataContainer = [String: ScopedMetadata]
public protocol Logger: Sendable {
func log(
_ message: @autoclosure () -> CustomStringConvertible,
_ level: LogLevel,
source: @autoclosure () -> String?,
file: StaticString,
type: Any.Type,
function: StaticString,
line: UInt,
metaData: ScopedMetadataContainer
)
}
// Default arguments
public extension Logger {
func log(
_ message: @autoclosure () -> CustomStringConvertible,
_ level: LogLevel = .debug,
source: @autoclosure () -> String? = nil,
file: StaticString = #fileID,
type: Any.Type,
function: StaticString = #function,
line: UInt = #line,
metaData: ScopedMetadataContainer = ScopedMetadataContainer()
) {
log(message(), level, source: source(), file: file, type: type, function: function, line: line, metaData: metaData)
}
}
/// A no-op logger
public struct DisabledLogger: Logger {
@inlinable
public func log(
_: @autoclosure () -> CustomStringConvertible,
_: LogLevel,
source _: @autoclosure () -> String?,
file _: StaticString,
type _: Any.Type,
function _: StaticString,
line _: UInt,
metaData _: ScopedMetadataContainer
) {}
}
/// A simple `print` logger suitable for debugging in terminal environments outside Xcode
public struct PrintLogger: Logger {
private let minLevel: LogLevel
private let colors: Bool
public init(minLevel: LogLevel = .info, colors: Bool = true) {
self.minLevel = minLevel
self.colors = colors
}
public func log(
_ message: @autoclosure () -> CustomStringConvertible,
_ level: LogLevel,
source _: @autoclosure () -> String?,
file _: StaticString,
type: Any.Type,
function: StaticString,
line _: UInt,
metaData _: ScopedMetadataContainer
) {
guard level >= minLevel else { return }
print("[\(colorCode(level))\(level)\(resetCode)] \(type).\(function) \(message())")
}
private func colorCode(_ level: LogLevel) -> String {
guard colors else { return "" }
switch level {
case .debug: return "\u{001B}[36m"
case .info: return "\u{001B}[94m"
case .warning: return "\u{001B}[33m"
case .error: return "\u{001B}[31m"
}
}
private var resetCode: String {
colors ? "\u{001B}[0m" : ""
}
}
/// A logger that logs to OSLog
/// - Parameter minLevel: The minimum level to log
/// - Parameter rtc: Whether to log WebRTC output
/// - Parameter ffi: Whether to log Rust FFI output
open class OSLogger: Logger, @unchecked Sendable {
private static let subsystem = "io.livekit.sdk"
private let queue = DispatchQueue(label: "io.livekit.oslogger", qos: .utility)
private var logs: [String: OSLog] = [:]
private lazy var rtcLogger = LKRTCCallbackLogger()
private let minLevel: LogLevel
public init(minLevel: LogLevel = .info, rtc: Bool = false, ffi: Bool = true) {
self.minLevel = minLevel
if rtc {
startRTCLogForwarding(minLevel: minLevel)
}
if ffi {
startFFILogForwarding(minLevel: minLevel)
}
}
deinit {
rtcLogger.stop()
}
public func log(
_ message: @autoclosure () -> CustomStringConvertible,
_ level: LogLevel,
source _: @autoclosure () -> String?,
file _: StaticString,
type: Any.Type,
function: StaticString,
line _: UInt,
metaData: ScopedMetadataContainer
) {
guard level >= minLevel else { return }
let message = message().description
func buildScopedMetadataString() -> String {
guard !metaData.isEmpty else { return "" }
return " [\(metaData.map { "\($0): \($1)" }.joined(separator: ", "))]"
}
let metadata = buildScopedMetadataString()
queue.async {
func getOSLog(for type: Any.Type) -> OSLog {
let typeName = String(describing: type)
if let cachedLog = self.logs[typeName] {
return cachedLog
}
let newLog = OSLog(subsystem: Self.subsystem, category: typeName)
self.logs[typeName] = newLog
return newLog
}
os_log("%{public}@", log: getOSLog(for: type), type: level.osLogType, "\(type).\(function) \(message)\(metadata)")
}
}
private func startRTCLogForwarding(minLevel: LogLevel) {
let rtcLog = OSLog(subsystem: Self.subsystem, category: "WebRTC")
rtcLogger.severity = minLevel.rtcSeverity
rtcLogger.start { message, severity in
os_log("%{public}@", log: rtcLog, type: severity.osLogType, message)
}
}
private func startFFILogForwarding(minLevel: LogLevel) {
Task(priority: .utility) { [weak self] in
guard self != nil else { return } // don't initialize global level when releasing
logForwardBootstrap(level: minLevel.logForwardFilter)
let ffiLog = OSLog(subsystem: Self.subsystem, category: "FFI")
let ffiStream = AsyncStream(unfolding: logForwardReceive)
for await entry in ffiStream {
guard self != nil else { return }
let message = "\(entry.target) \(entry.message)"
os_log("%{public}@", log: ffiLog, type: entry.level.osLogType, message)
}
}
}
}
// MARK: - Loggable
/// Allows to extend with custom `log` method which automatically captures current type (class name).
public protocol Loggable {}
extension Loggable {
func log(_ message: CustomStringConvertible? = nil,
_ level: LogLevel = .debug,
file: StaticString = #fileID,
function: StaticString = #function,
line: UInt = #line)
{
Self.log(message ?? "",
level,
file: file,
function: function,
line: line)
}
static func log(_ message: CustomStringConvertible? = nil,
_ level: LogLevel = .debug,
file: StaticString = #fileID,
function: StaticString = #function,
line: UInt = #line)
{
sharedLogger.log(message ?? "",
level,
file: file,
type: Self.self,
function: function,
line: line)
}
}
// MARK: - Level
@objc
@frozen
public enum LogLevel: Int, Sendable, Comparable, CustomStringConvertible {
case debug
case info
case warning
case error
@inlinable
var osLogType: OSLogType {
switch self {
case .debug: .debug
case .info: .info
case .warning: .default
case .error: .error
}
}
var rtcSeverity: LKRTCLoggingSeverity {
switch self {
case .debug: .verbose
case .info: .info
case .warning: .warning
case .error: .error
}
}
var logForwardFilter: LogForwardFilter {
switch self {
case .debug: .debug
case .info: .info
case .warning: .warn
case .error: .error
}
}
@inlinable
public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool {
lhs.rawValue < rhs.rawValue
}
public var description: String {
switch self {
case .debug: "Debug"
case .info: "Info"
case .warning: "Warning"
case .error: "Error"
}
}
}
extension LKRTCLoggingSeverity {
var osLogType: OSLogType {
switch self {
case .verbose: .debug
case .info: .info
case .warning: .default
case .error: .error
case .none: .debug
@unknown default: .debug
}
}
}
extension LogForwardLevel {
var osLogType: OSLogType {
switch self {
case .error: .error
case .warn: .default
case .info: .info
case .debug, .trace: .debug
@unknown default: .debug
}
}
}