您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页iOS 实时读取Console NSLog日志

iOS 实时读取Console NSLog日志

来源:二三娱乐

进门直接贴代码

- (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);
}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务