我正在尝试将我的日志同时发送到 Xcode 控制台和带有 Swift 的文件。我找到的解决方案要么是控制台,要么是仅重定向到文件。
如何让日志转到两者?
注意:一些日志来自我应用程序中的其他 3rd 库和框架,而不仅仅是 Swift 的print()
。因此,在应用程序上使用宏或日志记录框架(如CocoaLumberjack(将无济于事。
例如,这会在调用时将控制台中的所有日志重定向到文件,然后控制台变为空
func logToFile() {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "app_log.txt"
let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)
freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stderr)
freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stdin)
freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stdout)
}
我已经稍微扩展了您的方法,现在您将给定的字符串写入输出文件并将其记录到控制台。
我喜欢有另一个函数,它处理给定的字符串,使用像这样的参数
__FILE__ - String - The name of the file in which it appears.
__LINE__ - Int - The line number on which it appears.
__COLUMN__ - Int - The column number in which it begins.
__FUNCTION__ - String - The name of the declaration in which it appears.
扩展方法现在可能如下所示。
func logToFile(message: String) -> Void {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "app_log.txt"
let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)
let fileUrl = URL(fileURLWithPath: logFilePath)
var error:NSError?
// simply create the file, here you could add first line or something
// just make sure it exists
if (!FileManager.default.fileExists(atPath: logFilePath)) {
let data = new Data();
do {
try data.write(to:fileUrl , options: .atomic)
} catch {
println("Can't create file (error)")
}
}
// start writing
if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {
let data = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
}
else {
}
// Now also print the result to console
print(message)
}