How to redirect the nslog output to file instead of console

Unicorn picture Unicorn · Jul 6, 2010 · Viewed 18.4k times · Source

I have cocoa application running on OS X. I have used NSLog for debugging purpose. Now I want to redirect the log statements to file instead of console.

I have used this method but it results logging in Console as well as in file.

- (BOOL)redirectNSLog
{
    // Create log file
    [@"" writeToFile:@"/NSLog.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
    id fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/NSLog.txt"];
    if (!fileHandle)    return NSLog(@"Opening log failed"), NO;
    [fileHandle retain];

    // Redirect stderr
    int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
    if (!err)   return  NSLog(@"Couldn't redirect stderr"), NO;

    return  YES;
}

Is it possible to not have log statement in console but only in file ??

Answer

user745098 picture user745098 · May 9, 2011

Step 1: Include following function in AppDelegate:

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

Step 2: Call this function at the start of function applicationDidFinishLaunchingWithOptions...

Thats it, Every NSLog() will now get redirected to this console.log file, which you can find in the documents directory.