Logging to a file on the iPhone

后端 未结 5 1583
暗喜
暗喜 2020-11-30 20:45

What would be the best way to write log statements to a file or database in an iPhone application?

Ideally, NSLog() output could be redirected to a file using freop

相关标签:
5条回答
  • 2020-11-30 21:21

    I've successfully used freopen(...) on the phone to re-direct output to my own file.

    0 讨论(0)
  • 2020-11-30 21:21

    This code works for me:

    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    #if TARGET_IPHONE_SIMULATOR == 0
        freopen([@"/tmp/my_logs.txt" fileSystemRepresentation], "w", stderr);
    #endif
    }
    
    0 讨论(0)
  • 2020-11-30 21:27

    This code works great for me..

    #if TARGET_IPHONE_SIMULATOR == 0
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"];
        freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
    #endif
    

    You can then get the log file off the iphone using the method outlined here http://blog.coriolis.ch/2009/01/09/redirect-nslog-to-a-file-on-the-iphone/#more-85

    Note that using freopen will STOP THE CONSOLE IN XCODE working.. however, for some reason the console you can view in xcode's organiser still works great.

    0 讨论(0)
  • 2020-11-30 21:34

    Consider using Cocoa Lumberjack. It's a light but flexible utility to replace NSLog functionality. In my opinion it's in the same class as Log4J, allowing for custom appenders and the like. It has an SQLite logger, for example.

    0 讨论(0)
  • 2020-11-30 21:37

    If you want to use Cocoa, NSString and NSData have methods for reading/writing to file and NSFileManager gives you file operations. Here's an example (should work on iPhone):

    NSData *dataToWrite = [[NSString stringWithString:@"String to write"] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"];
    
    // Write the file
    [dataToWrite writeToFile:path atomically:YES];
    
    // Read the file
    NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path];  
    
    // Check if file exists
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager fileExistsAtPath:path]; // Returns a BOOL    
    
    // Remove the file
    [fileManager removeItemAtPath:path error:NULL];
    
    // Cleanup
    [stringFromFile release];
    [fileManager release];
    
    0 讨论(0)
提交回复
热议问题