How to redirect STDOUT to a NSTextView?

后端 未结 3 804
旧巷少年郎
旧巷少年郎 2021-02-15 14:13

Could anybody show me how to redirect the Stdout to a NSTextView?

and whether the info print by NSLog belong to the std?

Thanks

3条回答
  •  生来不讨喜
    2021-02-15 14:40

    if the goal is to handle your NSLog output only, not the system generated error logs, there is an other way to do so, here is a code to overclass NSLog. This code is only printing the log and some extra information on stderr instead of the usual NSLog output, but you can make any changes that suites your needs inside the HyperLog function :

    HyperLog.h

    #import 
    
    #ifdef HYPER_LOG
    #define NSLog(args...) HyperLog(__FILE__,__LINE__,__PRETTY_FUNCTION__,args);
    #else
    #define NSLog(x...)
    #endif
    
    void HyperLog(const char *file, int lineNumber, const char *functionName, NSString *format, ...);
    

    Hyperlog.m

    #import "HyperLog.h"
    
    void HyperLog(const char *file, int lineNumber, const char *functionName, NSString *format, ...)
    {
        va_list ap;
        va_start (ap, format);
        if (![format hasSuffix: @"\n"])
        {
            format = [format stringByAppendingString: @"\n"];
        }
    
        NSString *body = [[NSString alloc] initWithFormat:format arguments:ap];
        va_end (ap);
         NSString *fileName = [[NSString stringWithUTF8String:file] lastPathComponent];
        char mesg[8192]="\0";
        NSDate *now =[NSDate date];
        NSString *dateString = [NSDateFormatter localizedStringFromDate:now dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterMediumStyle];
        if ( sprintf( mesg, "<%s.%03.0f> : %s\n<%s : %d - %s>\n", [dateString UTF8String],roundf(fmod( [now timeIntervalSinceReferenceDate], 1 ) * 1000), [body UTF8String], [fileName UTF8String],
                     lineNumber,
                functionName) < 0 ) printf("message creation failed\n");
        fprintf(stderr, "%s", mesg );
    }
    

    You then only need to put these 2 lines on top of any of your program file to have it work

    #define HYPER_LOG
    #import "HyperLog.h"
    

    I tried to use the above code from Thomas to have the result data of a system generated error log written to a text file using a C function, that works properly in other contexts, but it keeps and crashing, and the error reason is lost in the process. Anyone has an idea why ?

提交回复
热议问题