Redirect NSLog to a file on the iPhone

If you need to debug your app when disconnected from your Mac (and from the console), redirect all your NSLog calls to a file so you can later read it.

The method below will create a file name « console.log » in the Documents folder of your application so you can later read it.

Just call this method in your program:

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

The log will never be erased, so use with caution.

Lire la suite…