-
Notifications
You must be signed in to change notification settings - Fork 283
/
Logging.swift
398 lines (341 loc) · 14.5 KB
/
Logging.swift
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#else
import Glibc
#endif
/// This is the protocol a custom logger implements.
public protocol LogHandler {
// This is the custom logger implementation's log function. A user would not invoke this but rather go through
// `Logger`'s `info`, `error`, or `warning` functions.
//
// An implementation does not need to check the log level because that has been done before by `Logger` itself.
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: StaticString, function: StaticString, line: UInt)
// This adds metadata to a place the concrete logger considers appropriate. Some loggers
// might not support this feature at all.
subscript(metadataKey _: String) -> Logger.Metadata.Value? { get set }
// All available metatdata
var metadata: Logger.Metadata { get set }
// The log level
var logLevel: Logger.Level { get set }
}
// This is the logger itself. It can either have value or reference semantics, depending on the `LogHandler`
// implementation.
public struct Logger {
@usableFromInline
var handler: LogHandler
public let label: String
internal init(label: String, _ handler: LogHandler) {
self.label = label
self.handler = handler
}
}
extension Logger {
@inlinable
public func log(level: Logger.Level, _ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
if self.logLevel >= level {
self.handler.log(level: level, message: message(), metadata: metadata(), file: file, function: function, line: line)
}
}
@inlinable
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.handler[metadataKey: metadataKey]
}
set {
self.handler[metadataKey: metadataKey] = newValue
}
}
@inlinable
public var metadata: Logger.Metadata {
get {
return self.handler.metadata
}
set {
self.handler.metadata = newValue
}
}
@inlinable
public var logLevel: Logger.Level {
get {
return self.handler.logLevel
}
set {
self.handler.logLevel = newValue
}
}
}
extension Logger {
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .debug, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .info, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .notice, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .warning, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .error, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .critical, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func alert(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .alert, message(), metadata: metadata(), file: file, function: function, line: line)
}
@inlinable
public func emergency(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.log(level: .emergency, message(), metadata: metadata(), file: file, function: function, line: line)
}
}
// This is the logging system itself, it's mostly used to obtain loggers and to set the type of the `LogHandler`
// implementation.
public enum LoggingSystem {
fileprivate static let lock = ReadWriteLock()
fileprivate static var factory: (String) -> LogHandler = StdoutLogHandler.init
fileprivate static var initialized = false
// Configures which `LogHandler` to use in the application.
public static func bootstrap(_ factory: @escaping (String) -> LogHandler) {
lock.withWriterLock {
precondition(!self.initialized, "logging system can only be initialized once per process.")
self.factory = factory
self.initialized = true
}
}
// for our testing we want to allow multiple bootstraping
internal static func bootstrapInternal(_ factory: @escaping (String) -> LogHandler) {
self.lock.withWriterLock {
self.factory = factory
}
}
}
extension Logger {
public typealias Metadata = [String: MetadataValue]
public enum MetadataValue {
case string(String)
case stringConvertible(CustomStringConvertible)
case dictionary(Metadata)
case array([Metadata.Value])
}
public enum Level: Int {
case debug = 7
case info = 6
case notice = 5
case warning = 4
case error = 3
case critical = 2
case alert = 1
case emergency = 0
}
public init(label: String) {
self = LoggingSystem.lock.withReaderLock { Logger(label: label, LoggingSystem.factory(label)) }
}
// this is to provide an escape hatch for situations one must use a custom factory instead of the gloabl one
// we do not expect this API to be used in normal circumstances, so if you find yourself using it make sure its for a good reason
public init(label: String, factory: (String) -> LogHandler) {
self = Logger(label: label, factory(label))
}
}
extension Logger.Level: Comparable {
public static func < (lhs: Logger.Level, rhs: Logger.Level) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687
// Then we could write it as follows and it would work under Swift 5 and not only 4 as it does currently:
// extension Logger.Metadata.Value: Equatable {
extension Logger.MetadataValue: Equatable {
public static func == (lhs: Logger.Metadata.Value, rhs: Logger.Metadata.Value) -> Bool {
switch (lhs, rhs) {
case (.string(let lhs), .string(let rhs)):
return lhs == rhs
case (.stringConvertible(let lhs), .stringConvertible(let rhs)):
return lhs.description == rhs.description
case (.array(let lhs), .array(let rhs)):
return lhs == rhs
case (.dictionary(let lhs), .dictionary(let rhs)):
return lhs == rhs
default:
return false
}
}
}
extension Logger {
public struct Message: ExpressibleByStringLiteral, Equatable, CustomStringConvertible {
public typealias StringLiteralType = String
private var value: String
public init(stringLiteral value: String) {
self.value = value
}
public var description: String {
return self.value
}
}
}
/// Ships with the logging module, used to multiplex to multiple logging handlers
public class MultiplexLogHandler: LogHandler {
private let lock = Lock()
private var handlers: [LogHandler]
public init(_ handlers: [LogHandler]) {
assert(handlers.count > 0)
self.handlers = handlers
}
public var logLevel: Logger.Level {
get {
return self.handlers[0].logLevel
}
set {
self.mutateHandlers { $0.logLevel = newValue }
}
}
public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: StaticString, function: StaticString, line: UInt) {
self.handlers.forEach { handler in
handler.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line)
}
}
public var metadata: Logger.Metadata {
get {
return self.handlers[0].metadata
}
set {
self.mutateHandlers { $0.metadata = newValue }
}
}
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.handlers[0].metadata[metadataKey]
}
set {
self.mutateHandlers { $0[metadataKey: metadataKey] = newValue }
}
}
private func mutateHandlers(mutator: (inout LogHandler) -> Void) {
var newHandlers = [LogHandler]()
self.handlers.forEach {
var handler = $0
mutator(&handler)
newHandlers.append(handler)
}
self.lock.withLock { self.handlers = newHandlers }
}
}
/// Ships with the logging module, really boring just prints something using the `print` function
internal struct StdoutLogHandler: LogHandler {
private let lock = Lock()
public init(label: String) {}
private var _logLevel: Logger.Level = .info
public var logLevel: Logger.Level {
get {
return self.lock.withLock { self._logLevel }
}
set {
self.lock.withLock {
self._logLevel = newValue
}
}
}
private var prettyMetadata: String?
private var _metadata = Logger.Metadata() {
didSet {
self.prettyMetadata = self.prettify(self._metadata)
}
}
public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: StaticString, function: StaticString, line: UInt) {
let prettyMetadata = metadata?.isEmpty ?? true ? self.prettyMetadata : self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new }))
print("\(self.timestamp()) \(level)\(prettyMetadata.map { " \($0)" } ?? "") \(message)")
}
public var metadata: Logger.Metadata {
get {
return self.lock.withLock { self._metadata }
}
set {
self.lock.withLock { self._metadata = newValue }
}
}
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.lock.withLock { self._metadata[metadataKey] }
}
set {
self.lock.withLock {
self._metadata[metadataKey] = newValue
}
}
}
private func prettify(_ metadata: Logger.Metadata) -> String? {
return !metadata.isEmpty ? metadata.map { "\($0)=\($1)" }.joined(separator: " ") : nil
}
private func timestamp() -> String {
var buffer = [Int8](repeating: 0, count: 255)
var timestamp = time(nil)
let localTime = localtime(×tamp)
strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime)
return buffer.withUnsafeBufferPointer {
$0.withMemoryRebound(to: CChar.self) {
String(cString: $0.baseAddress!)
}
}
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension Logger.MetadataValue: CustomStringConvertible {
public var description: String {
switch self {
case .dictionary(let dict):
return dict.mapValues { $0.description }.description
case .array(let list):
return list.map { $0.description }.description
case .string(let str):
return str
case .stringConvertible(let repr):
return repr.description
}
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByStringInterpolation {
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByDictionaryLiteral {
public typealias Key = String
public typealias Value = Logger.Metadata.Value
public init(dictionaryLiteral elements: (String, Logger.Metadata.Value)...) {
self = .dictionary(.init(uniqueKeysWithValues: elements))
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Logger.Metadata.Value
public init(arrayLiteral elements: Logger.Metadata.Value...) {
self = .array(elements)
}
}