iOS Swift:将打印和调试打印写入文件 [英] iOS Swift: write print and debug prints into a file
问题描述
晚上,是否可以将所有打印和调试打印保存到文件中?
Evening, is it possible to save in a file all the prints and the debug prints?
即使没有从Xcode启动,我也希望获得我的应用程序执行的日志.
I would like to have the logs of what my application does even when is not launched from Xcode.
我当时正在考虑重写print和debugPrint方法,并将输入内容写入文件中.
I was thinking to override the print and the debugPrint methods and to write the input into a file.
谢谢
推荐答案
Swift标准库中有一些方法:
There are methods in Swift Standard Library:
func print<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream
和
func debugPrint<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream
您可以创建一个实现 TextOutputStream
的对象,该对象会将消息保存到您选择的文件中.如果您在代码库中已有打印,这将非常有用.然后,您可以将其他参数添加到它们中.请记住,这些打印将停止记录到标准输出(控制台).
You can create an object that implements TextOutputStream
that will save a message to a file of your choice. This is very useful if you already have existing prints in the codebase. You can then just add the additional parameter to them. Remember that those prints will then stop logging to the standard output (console).
示例:
final class LogDestination: TextOutputStream {
private let path: String
init() {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
path = paths.first! + "/log"
}
func write(_ string: String) {
if let data = string.data(using: .utf8), let fileHandle = FileHandle(forWritingAtPath: path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(data)
}
}
}
然后
// I would probably use Singleton for this
var dest = LogDestination()
print("My test message", to: &dest)
这篇关于iOS Swift:将打印和调试打印写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!