如何捕获stderr输出并通过目标c中的POST请求将消息发送到远程日志文件?

时间:2019-01-11 11:32:43

标签: ios objective-c

我有一个简单的网络服务,可以在线监听发布请求。它将写为本地参数的字符串发送到本地文件。

现在,我有一个ios应用程序,我想将应用程序stderr的每条消息发送到Web服务,以将错误记录在在线文件中,并能够远程实时查看应用程序错误。

我知道我可以将stderr消息重定向到这样的文件(设备本地)

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

我知道我可以这样发送帖子请求,因此将字符串'errorString'写入远程日志

    NSString *errorString=@"errorIOS";
    NSString *errorData =[NSString stringWithFormat:@"errorString=%@",errorString];
    NSData *postData = [errorData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://mywebserviceurl"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

但是,如果我想重定向stderr消息,以便每次出现错误消息时,都会触发对我的Web服务的发布请求,并将消息写入远程日志,而不是写入设备本地文件?

1 个答案:

答案 0 :(得分:1)

使用此代码将管道附加到stderr上

RGB

因此添加功能可以达到结果

NSPipe* pipe = [NSPipe pipe];
NSFileHandle* pipeReadHandle = [pipe fileHandleForReading];
dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stderr));
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, [pipeReadHandle fileDescriptor], 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_event_handler(source, ^{
    void* data = malloc(4096);
    ssize_t readResult = 0;
    do
    {
        errno = 0;
        readResult = read([pipeReadHandle fileDescriptor], data, 4096);
    } while (readResult == -1 && errno == EINTR);
    if (readResult > 0)
    {
        //AppKit UI should only be updated from the main thread
        dispatch_async(dispatch_get_main_queue(),^{
            NSString* stdOutString = [[NSString alloc] initWithBytesNoCopy:data length:readResult encoding:NSUTF8StringEncoding freeWhenDone:YES];
            NSAttributedString* stdOutAttributedString = [[NSAttributedString alloc] initWithString:stdOutString];
            [appFunctions postDataToRemoteLogWithMessage:stdOutAttributedString];
        });
    }
    else{free(data);}
});
dispatch_resume(source);