关闭特定对象的控制台日志记录

Mar*_*rle 12 iphone xcode logging objective-c mpmovieplayercontroller

这有点令人讨厌:自从我开始使用MPMoviePlayerController以来,控制台中的MPAVController信息过满了.例如:

[MPAVController] Autoplay: _streamLikelyToKeepUp: 1 -> 1
[MPAVController] Autoplay: Disabling autoplay
Run Code Online (Sandbox Code Playgroud)

这有点烦人,因为我总是要搜索自己的记录信息.有没有办法关闭特定对象或框架的日志记录?

det*_*zed 10

我不认为这种过滤是开箱即用的.但是可以将stderr(由其使用NSLog)重定向到管道中,从后台线程中的该管道读取,然后打印通过过滤器的消息stdout(也由调试器捕获).这段代码完成了这项工作:

int main(int argc, char *argv[])
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^(void) {
        size_t const BUFFER_SIZE = 2048;

        // Create a pipe
        int pipe_in_out[2];
        if (pipe(pipe_in_out) == -1)
            return;

        // Connect the 'in' end of the pipe to the stderr
        if (dup2(pipe_in_out[1], STDERR_FILENO) == -1)
            return;

        char *buffer = malloc(BUFFER_SIZE);
        if (buffer == 0)
            return;

        for (;;)
        {
            // Read from the 'out' end of the pipe
            ssize_t bytes_read = read(pipe_in_out[0], buffer, BUFFER_SIZE);
            if (bytes_read <= 0)
                break;

            // Filter and print to stdout
            if (should_show(buffer)) // TODO: Apply filters here
                fwrite(buffer, 1, bytes_read, stdout);
        }

        free(buffer);
        close(pipe_in_out[1]);
    });

    // Rest of main
}
Run Code Online (Sandbox Code Playgroud)

请注意,此代码非常简单,无法处理所有极端情况.首先,它捕获所有stderr输出而不仅仅是NSLog.也许这可以通过检查内容来过滤掉.NSLog输出始终以日期和时间开始.

此代码的第二个问题是它不会尝试拆分/连接从管道读取的字符串.无法保证NSLog每次阅读都会有一个.他们可能会聚在一起或者太长并且会分裂.要处理这个问题,需要额外处理从管道读取的数据.

无论如何,出于许多实际目的,这应该足够了.