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.

Once you have tested your app in the filed, reconnect your phone to your Mac and in Xcode, open the Organizer.
In the Summary panel, you have the list of all the apps on your phone. Expand the one you’re debugging, and you’ll a package named « Application Data ».

Xcode Organizer
Xcode Organizer

Click the arrow on the right of its name and save this. You’ll end with a folder with a name of your Bundle Identifier followed by a date.

Inside this folder you’ll find your Documents Folder, which should contain the console.log.

Happy debugging.

6 réflexions au sujet de “Redirect NSLog to a file on the iPhone”

  1. This code doesn’t work for me on iOS 8.0 with XCode 6.4.
    Doesn’t it required any setting on iPhone..

  2. This is a fantastic piece of information. Now I can read my NSlog output from an ‘.ipa’ file.

    You say that you can never erase the file?
    But, surely, you can just delete the file by using;

    – (void)removeFile:(NSString *)filename{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
    NSError *error;
    BOOL success = [fileManager removeItemAtPath:filePath error:&error];
    if (success) {
    NSLog(@ »File deleted successfully »);
    }
    else{
    NSLog(@ »Could not delete file: %@ « ,[error localizedDescription]);
    }
    }

Laisser un commentaire