Possible to write swift println logs into file too?

天大地大妈咪最大 提交于 2020-01-29 17:38:09

问题


Is it an easy way to write logs into a text file too? I need a crash log to analyse when something went wrong. But I already use println al around in the code.


回答1:


Use String.writeToFile(<#path: String#>, atomically: <#Bool#>, encoding: <#NSStringEncoding#>, error: <#NSErrorPointer#>)

You could add this:

#if DEBUG
func println(s:String) {
  var error:NSError? = nil
  let path = "/Users/<me>/dump.txt"
  var dump = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)!
  "\(dump)\n\(s)".writeToFile(path, atomically:true, encoding:NSUTF8StringEncoding, error:&error)
}
#endif

See the #if DEBUG answer on SO how to use this compiler flag.




回答2:


For swift 3, change Thomas Killan's code like this

func println(s:String) {
    let path = "/Users/<me>/dump.txt"
    var dump = ""
    if FileManager.default.fileExists(atPath: path) {
        dump =  try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
    }
    do {
        // Write to the file
        try  "\(dump)\n\(s)".write(toFile: path, atomically: true, encoding: String.Encoding.utf8)

    } catch let error as NSError {
        print("Failed writing to log file: \(path), Error: " + error.localizedDescription)
    }
}



回答3:


Unfortunately, using a println()-based solution will not result in output being captured by the Apple System Log (ASL).

The ASL is the logging facility provided by the Mac OS and iOS that is used by NSLog() (and on a Mac is visible through the Console application). Because NSLog() uses ASL, log entries recorded by NSLog() will be visible through the device console. Messages logged through println() will not be captured in ASL, and as a result, provide no opportunity to go back to the console for diagnostic purposes after something has happened.

The CleanroomLogger open-source project provides an extensible Swift API that you can use to do what you want. You would just implement a LogRecorder and specify it in the configuration in addition to the ASLLogRecorder.




回答4:


I modified a little your function to be global and add to save a log per day.

public func debugPrint(s:String) {

var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let dateString = formatter.string(from: Date())
let fileName = "\(dateString).log"
let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)
var dump = ""
if FileManager.default.fileExists(atPath: logFilePath) {
    dump =  try! String(contentsOfFile: logFilePath, encoding: String.Encoding.utf8)
}
do {
    // Write to the file
    try  "\(dump)\n\(Date()):\(s)".write(toFile: logFilePath, atomically: true, encoding: String.Encoding.utf8)

} catch let error as NSError {
    print("Failed writing to log file: \(logFilePath), Error: " + error.localizedDescription)
}
}


来源:https://stackoverflow.com/questions/28114110/possible-to-write-swift-println-logs-into-file-too

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!