-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
Logging.swift
49 lines (43 loc) · 1.59 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
import Combine
import Foundation
import os.log
final actor Logging {
static let shared = Logging()
private let logPublisher = PassthroughSubject<() -> String, Never>()
private var monitorObservation: Cancellable?
var monitoringLog: Bool {
consoleObservation != nil || monitorObservation != nil
}
func log(_ message: @Sendable @escaping @autoclosure () -> String) {
if monitoringLog {
logPublisher.send(message)
}
}
private var consoleObservation: Cancellable?
func setupConsoleLogging() {
consoleObservation = logPublisher
.sink { message in
os_log("%{public}@", message())
}
log(">>> Will log to the system log, as '-useSystemLog' has been specified")
}
func setupMonitorCallback(_ block: (@MainActor (NSAttributedString) -> Void)?) {
if let block {
monitorObservation = logPublisher
.sink { message in
let dateString = Date().formatted(Date.Formatters.logDateFormat)
#if canImport(AppKit)
let labelColor = COLOR_CLASS.labelColor
#else
let labelColor = COLOR_CLASS.label
#endif
let logString = NSAttributedString(string: ">>> \(dateString)\n\(message())\n\n", attributes: [.foregroundColor: labelColor])
Task { @MainActor in
block(logString)
}
}
} else {
monitorObservation = nil
}
}
}