Redirect NSLog to File in Swift not working

The absoluteString property of an URL produces an URL string, e.g.

    file:///path/to/file.txt

which is not suitable as argument to freopen().
To get the file path as a string, use path instead:

let logPath = dir.appendingPathComponent(file).path

Better, use the dedicated method to pass an URLs path to a system call:

let logFileURL = dir.appendingPathComponent(file)
logFileURL.withUnsafeFileSystemRepresentation {
    _ = freopen($0, "a+", stderr)
}

Leave a Comment