简体   繁体   中英

Save NSLog into a Local File

I'm learning how to develop for iPhone and i need to save de NSLog output on a local file on my machine to analyse the result in because I`ll run the application for a long time and I need to check after some hours running what was the output (and I want to save the output file on my machine from time to time, for example after every 30min).

How can I save the xcode output into a file?

Possibly not what you want, but I use this:

- (void)logIt:(NSString *)string {
    // First send the string to NSLog
    NSLog(@"%@", string);

    // Setup date stuff
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-dd-MM"];
    NSDate *date = [NSDate date];

    // Paths - We're saving the data based on the day.
    NSString *path = [NSString stringWithFormat:@"%@-logFile.txt", [formatter stringFromDate:date]];
    NSString *writePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];

    // We're going to want to append new data, so get the previous data.
    NSString *fileContents = [NSString stringWithContentsOfFile:writePath encoding:NSUTF8StringEncoding error:nil];

    // Write it to the string
    string = [NSString stringWithFormat:@"%@\n%@ - %@", fileContents, [formatter stringFromDate:date], string];

    // Write to file stored at: "~/Library/Application\ Support/iPhone\ Simulator/*version*/Applications/*appGUID*/Documents/*date*-logFile.txt"
    [string writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

This writes the data into a file on your device (a daily file). If you want it to reset after each session you can surely modify the code to do that.

And of course you'll have to change all your existing NSLog() calls to use [self logIt:] instead.

This also works on a real device (but the file location is different of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM