Release 构建下完全静默(isEnabled 固定 false), Debug 构建下通过 _enabled 开关控制,默认开启。 Co-Authored-By: Claude <noreply@anthropic.com>
61 lines
1.7 KiB
Swift
61 lines
1.7 KiB
Swift
import Foundation
|
|
|
|
enum RDEPUBBackgroundTrace {
|
|
|
|
static var isEnabled: Bool {
|
|
#if DEBUG
|
|
return _enabled
|
|
#else
|
|
return false
|
|
#endif
|
|
}
|
|
|
|
static var _enabled = true
|
|
|
|
static func log(_ scope: String, _ message: String) {
|
|
guard isEnabled else { return }
|
|
let threadRole = Thread.isMainThread ? "main" : "bg"
|
|
|
|
let threadName = resolvedThreadName()
|
|
|
|
let queueLabel = resolvedQueueLabel()
|
|
print("[EPUB][\(scope)][\(threadRole)][queue=\(queueLabel)][thread=\(threadName)] \(message)")
|
|
}
|
|
|
|
static func measure<T>(_ scope: String, _ message: String, work: () throws -> T) rethrows -> T {
|
|
guard isEnabled else { return try work() }
|
|
let startedAt = CFAbsoluteTimeGetCurrent()
|
|
log(scope, "START \(message)")
|
|
do {
|
|
|
|
let result = try work()
|
|
|
|
let elapsedMs = Int((CFAbsoluteTimeGetCurrent() - startedAt) * 1000)
|
|
log(scope, "END \(message) elapsedMs=\(elapsedMs)")
|
|
return result
|
|
} catch {
|
|
|
|
let elapsedMs = Int((CFAbsoluteTimeGetCurrent() - startedAt) * 1000)
|
|
log(scope, "FAIL \(message) elapsedMs=\(elapsedMs) error=\(error)")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
private static func resolvedThreadName() -> String {
|
|
|
|
if let name = Thread.current.name, !name.isEmpty {
|
|
return name
|
|
}
|
|
|
|
if Thread.isMainThread {
|
|
return "main"
|
|
}
|
|
|
|
return String(describing: Unmanaged.passUnretained(Thread.current).toOpaque())
|
|
}
|
|
|
|
private static func resolvedQueueLabel() -> String {
|
|
String(validatingUTF8: __dispatch_queue_get_label(nil)) ?? "unknown"
|
|
}
|
|
}
|