NSLog() to both console and file

后端 未结 2 1043
感动是毒
感动是毒 2020-12-08 20:20

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:

         


        
相关标签:
2条回答
  • 2020-12-08 20:36

    The way we have implemented is:

    if (!isatty(STDERR_FILENO)) {
        // Redirection code
    }
    

    This is based on general assumption that if a console is attached, you do not need to store those logs in the file since you are already debugging. So whenever the console is attached, logs will be printed there, otherwise saved to a file.

    0 讨论(0)
  • 2020-12-08 20:47

    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

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