5

Evening, is it possible to save in a file all the prints and the debug prints?

I would like to have the logs of what my application does even when is not launched from Xcode.

I was thinking to override the print and the debugPrint methods and to write the input into a file.

Thanks

Andrea Miotto
  • 7,084
  • 8
  • 45
  • 70
  • Possible helpful: https://stackoverflow.com/questions/41923968/swift-stderr-and-stout-into-single-file, https://stackoverflow.com/questions/41680004/redirect-nslog-to-file-in-swift-not-working – Martin R Nov 20 '18 at 12:11
  • check https://stackoverflow.com/a/7307150/2025766 – FedeH Nov 20 '18 at 12:12

3 Answers3

4

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

and

func debugPrint<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : 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).

Documentation for print

Documentation for debugPrint

Example:

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

And then

// I would probably use Singleton for this
var dest = LogDestination()
print("My test message", to: &dest)
Tomasz Bąk
  • 6,124
  • 3
  • 34
  • 48
2

Its possible to write all print/debugPrint logs to file in iOS. Use below for writing debug logs to files.

Note: If you are using the below code logs will not print on console.

func writeIntoFile() {
    if let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
        let filePath = documentDirectoryPath + "/logfile.txt"
        freopen(filePath.cString(using: .ascii), "a", stderr)
    }
}
iOS_Maccus
  • 377
  • 1
  • 11
1

I think you want your logs into an external file. If so, then you can try this:

func redirectLogs(flag:Bool)  {
    if flag {
        if let documentsPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
            let logPath = documentsPathString.appending("app.log")
            freopen(logPath.cString(using: String.Encoding.ascii), "a+",stderr)
        }
    }
}
Anand Kore
  • 1,300
  • 1
  • 15
  • 33