74 lines
3.2 KiB
Swift
74 lines
3.2 KiB
Swift
import Darwin
|
|
import Foundation
|
|
import OSLog
|
|
|
|
/// Debug/Release 共用简洁日志出口,序列化输出完整 JSON,避免并发日志互相穿插。
|
|
enum APIConsoleDiagnostics {
|
|
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "API")
|
|
private static let droneDockLogger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
|
|
private static let outputWriter = APIConsoleOutputWriter()
|
|
|
|
/// Xcode 附加调试时输出一个完整 JSON;脱离调试器时继续写入系统日志。
|
|
static func write(_ message: String) {
|
|
output(message, logger: logger)
|
|
}
|
|
|
|
/// 保留机巢原有系统日志 category,正文格式与其它模块一致。
|
|
static func writeDroneDock(_ message: String) {
|
|
output(message, logger: droneDockLogger)
|
|
}
|
|
|
|
private static func output(_ message: String, logger: Logger) {
|
|
guard let text = APIConsoleFormat.render(message) else { return }
|
|
outputWriter.write(text, prefersStandardOutput: isDebuggerAttached || isatty(STDOUT_FILENO) != 0) { text in
|
|
// 保留独立运行 Release 包的系统日志可见性,不加 session/entry/part 等包装。
|
|
for chunk in DroneDockDiagnostics.chunks(text) { logger.notice("\(chunk, privacy: .public)") }
|
|
}
|
|
}
|
|
|
|
private static var isDebuggerAttached: Bool {
|
|
var info = kinfo_proc()
|
|
var size = MemoryLayout<kinfo_proc>.stride
|
|
var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
|
|
return sysctl(&name, 4, &info, &size, nil, 0) == 0
|
|
&& (info.kp_proc.p_flag & P_TRACED) != 0
|
|
}
|
|
}
|
|
|
|
/// 串行写入日志;Xcode 输出通道断开后,本次运行改用系统日志,写入错误不能中断业务。
|
|
final class APIConsoleOutputWriter: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var standardOutputFailed = false
|
|
private let writeStandardOutput: @Sendable (Data) throws -> Void
|
|
|
|
/// 注入可失败的输出通道,以便使用隔离文件句柄验证断连及回退。
|
|
init(writeStandardOutput: @escaping @Sendable (Data) throws -> Void = {
|
|
try APIConsoleOutputWriter.write($0, to: .standardOutput)
|
|
}) {
|
|
self.writeStandardOutput = writeStandardOutput
|
|
}
|
|
|
|
/// 完整记录只走一个出口;stdout 失败时把原始记录交给系统日志,不再尝试损坏的通道。
|
|
func write(_ text: String, prefersStandardOutput: Bool, fallback: (String) -> Void) {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
if prefersStandardOutput && !standardOutputFailed {
|
|
do {
|
|
try writeStandardOutput(Data((text + "\n").utf8))
|
|
return
|
|
} catch {
|
|
standardOutputFailed = true
|
|
}
|
|
}
|
|
fallback(text)
|
|
}
|
|
|
|
/// 使用可抛 Swift 错误的写入 API,并把断管转成 EPIPE,避免 NSException 或 SIGPIPE 退出进程。
|
|
static func write(_ data: Data, to handle: FileHandle) throws {
|
|
guard fcntl(handle.fileDescriptor, F_SETNOSIGPIPE, 1) != -1 else {
|
|
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
|
|
}
|
|
try handle.write(contentsOf: data)
|
|
}
|
|
}
|