将进程stdout重定向到Swift中的Apple System Log Facility

时间:2018-02-06 08:43:55

标签: swift macos logging

我正在为macOS构建一个Swift应用程序来启动一个子进程。此子流程将有用信息记录到stdout,我在Xcode控制台中看到它。

我现在想要实现的是将子流程stdout重定向到Apple Log Facility,以便我们可以在部署应用程序时访问数据。

基本上,这个:

let task = Process()
task.launchPath = "subprocess"
task.standardOutput = // AppleSystemLogPipe
task.launch()

但我不知道如何引用Apple System Log Pipe。这有什么线索吗?

祝你好运!

1 个答案:

答案 0 :(得分:0)

我终于设法做到了这一点。基本上,我们定义一个Pipe来捕获进程输出,并在一个处理程序中,使用读取的数据调用操作系统函数os_log

let pipe = Pipe()
let outHandle = pipe.fileHandleForReading

outHandle.readabilityHandler = { pipe in
    if let line = String(data: pipe.availableData, encoding: .utf8) {
        // Define the placeholder as public, otherwise the Console obfuscate it
        os_log("%{public}@", line)
    }
}

let task = Process()
task.launchPath = "subprocess"
task.standardOutput = pipe // Redirect stdout to our pipe
task.launch()

在开发中,它显示在Xcode控制台中;部署后,它将重定向到Apple Log System。