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)