4

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It would be more effective to open a file for appending, instead of re-reading and -writing the entire contents for each println() ...
Yes sure. This was a hot shot, but performance isn't in question here and you can change that anyways if you like easily.
4

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)
    }
}

Comments

2

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.

Comments

1

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)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.