Search code examples
objective-cnslog

NSLog() to both console and file


I would like to redirect NSog() to file, but still to see the output in console. I am aware that stderr can be redirected to file using:

freopen("file.log", "a+", stderr);

but after redirecting it to file, the log is no more shown in the console output.

I could build a custom wrapper around NSLog() but I would not get logged crash logs that are written to stderr in the moment of app crash.

I was also experimenting with dup() and other methods for duplicating file descriptors, but the output was ether in file or in console, never in both.

Similar questions was asked here: Write stderr on iPhone to both file and console but without accepted answer, or with suggestion to use a NSLog() wrapper.

Has anyone an idea on how to manage this work? Thanx in advance.

UPDATE: The most important part of redirecting is to have system error logs (stderr) written to both console and file.


Solution

  • According to the docs, you will need a custom log facility.

    You need at a minimum, a function that takes variadic arguments and printd to NSLog and fprintf, something like:

    void myLog(NSString* format, ...)
    {
        va_list argList;
        va_start(argList, format);
        NSString* formattedMessage = [[NSString alloc] initWithFormat: format arguments: argList];
        va_end(argList);
        NSLog(@"%@", formattedMessage);
        fprintf(myFileDescriptor, "%s\n", [formattedMessage UTF8String]);
        [formattedMessage release]; // if not on ARC
    }
    

    Or there are Cocoa logging frameworks.

    Looking for a Specific Cocoa Logging Framework