我正在尝试将我的日志连接到Xcode控制台和带有 Swift 的文件。我找到的解决方案是控制台或仅重定向到文件。
如何将日志转到两者?
注意:有些日志来自我应用中的其他第3个库和框架,而不仅仅是Swift的print()
。因此,在应用程序上使用像CocoaLumberjack这样的宏或日志框架将无济于事。
e.g。这将在调用时将控制台中的所有日志重定向到文件,然后控制台变为空
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)
}
答案 0 :(得分:0)
我已经扩展了你的方法,现在你将一个给定的字符串写入输出文件并将其记录到控制台。
我喜欢使用另一个处理给定字符串的函数来使用像
这样的参数__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)
}