How do I redirect all errors, including uncaught exceptions, NSLog calls, and other logs, to a log file on Mac OS X?

后端 未结 3 1546
忘掉有多难
忘掉有多难 2020-12-15 21:48

I am attempting to find a logging framework for a Cocoa application, written in ObjC.

What I\'ve attempted so far:

  1. Use NSLog, but then realise that it
相关标签:
3条回答
  • 2020-12-15 22:11

    You can use the Foundation function NSSetUncaughtExceptionHandler to set a callback function that will handle all uncaught exceptions:

    void CustomLogger(NSString *format, ...) {
       //do other awesome logging stuff here...
    }
    
    void uncaughtExceptionHandler(NSException *exception) {
       //do something useful, like this:
       CustomLogger(@"%@", [exception reason]);
    }
    
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    

    For NSLog, you can use a macro to override it :)

    #define NSLog(...) CustomLogger(__VA_ARGS__);
    
    0 讨论(0)
  • 2020-12-15 22:18

    You can redirect standard error output to a file. Here is the method that redirects console output into a file in application’s Documents folder. This can be useful when you want to test your app outside your development studio, unplugged from your mac.

    -(void) redirectNSLogToDocuments {
     NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [allPaths objectAtIndex:0];
     NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"yourFile.txt"];
     freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
    }
    

    After executing this method all output generated by NSLog will be forwarded to specified file. To get your saved file open Organizer, browse application’s files and save Application Data somewhere in your file system, than simply browse to Documents folder.

    0 讨论(0)
  • 2020-12-15 22:19

    You can intercept NSLog() messages (but not ASL in general) using _NSSetLogCStringFunction(). It’s documented here for WebObjects 4 for Windows, but it exists in current Mac OS and iOS releases too. However, it’s a private function that may go away at any time, so you shouldn’t rely on it in released code.

    If you want to be able to safely do this for non-debug builds, I suggest duplicating this enhancement request on Radar.

    0 讨论(0)
提交回复
热议问题