3

I'm looking for the Swift equivalent of the following Objective C common code. In Objective C we had the following to redirect logging to the document folder instead of to the console:

- (void) redirectConsoleLogToDocumentFolder
{
 NSArray *paths = 
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logPath = [documentsDirectory
stringByAppendingPathComponent:@"console.log"];
freopen([logPath 
cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

How is that done in Swift 2 ?

Chaim Friedman
  • 720
  • 6
  • 24

2 Answers2

11

I suggest to read about logging in swift

func redirectConsoleLogToDocumentFolder() {
    var paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    var documentsDirectory: NSString = paths[0]
    var logPath: NSString = documentsDirectory.stringByAppendingPathComponent("console.log")
    var cstr = (logPath as NSString).UTF8String
    freopen(cstr, "a+", stderr)
}
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109
  • Thanks. It's throwing errors but at least I have what to work with now. The 3 errors are that both NSDocumentDirectory and NSDomainMask are 'unresolved identifiers', and 'stringByAppendingPathComponent' is unavailable: Use URLByAppendingPathComponent on NSURL instead. – Chaim Friedman Dec 01 '15 at 17:57
  • @Mt.T I am using the code you provided to redirect stdout to a file. When I do so I observe that print() no longer comes to the console (good) and that there is a file associated with my app that I can access via iTunes (good). BUT, the size of the file is 0. Any thoughts? – Verticon Dec 07 '15 at 19:29
  • @TejaNandamuri, I am not getting any text into a log file. – Gautam Sareriya Jul 17 '17 at 12:33
  • works like a charm, I had to modify this `let documentsDirectory: NSString = paths[0] as! NSString` You can access such log file from mac using https://stackoverflow.com/a/26379551/5414535 – Josef Vancura Nov 28 '17 at 10:10
8

An updated answer for Swift 3.0

if let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
    let documentsDirectory = NSURL(fileURLWithPath: path)
    let logPath = documentsDirectory.appendingPathComponent("console.log")!
    freopen(logPath.absoluteString, "a+", stderr)
}
HughHughTeotl
  • 5,439
  • 3
  • 34
  • 49