美文网首页
iOS 实时读取Console NSLog日志

iOS 实时读取Console NSLog日志

作者: vicxxc | 来源:发表于2016-08-26 15:10 被阅读147次

进门直接贴代码

- (void)log{
    int fildes[2];
    int fd = STDERR_FILENO;
    pipe(fildes);  // [0] is read end of pipe while [1] is write end
    dup2(fildes[1], fd);  // Duplicate write end of pipe "onto" fd (this closes fd)
    close(fildes[1]);  // Close original write end of pipe
    fd = fildes[0];  // We can now monitor the read end of the pipe
    
    char* buffer = malloc(1024);
    NSMutableData* data = [[NSMutableData alloc] init];
    fcntl(fd, F_SETFL, O_NONBLOCK);
    self.source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    dispatch_source_set_cancel_handler(self.source, ^{
        free(buffer);
    });
    dispatch_source_set_event_handler(self.source, ^{
        @autoreleasepool {
            
            while (1) {
                ssize_t size = read(fd, buffer, 1024);
                if (size <= 0) {
                    break;
                }
                [data appendBytes:buffer length:size];
                if (size < 1024) {
                    break;
                }
            }
            NSString *aString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            //            printf("aString = %s",[[aString substringFromIndex:30] UTF8String]);
            //            NSLog(@"aString = %@",aString);
            //读到了日志,可以进行我们需要的各种操作了
            
        }
    });
    dispatch_resume(self.source);
}

相关文章

网友评论

      本文标题:iOS 实时读取Console NSLog日志

      本文链接:https://www.haomeiwen.com/subject/pmrnsttx.html