如何重定向nslog输出到文件而不是控制台

问题描述:

我有在OS X上运行的可可应用程序。我使用NSLog进行调试。现在我想将日志语句重定向到文件而不是控制台。

I have cocoa application running on OS X. I have used NSLog for debugging purpose. Now I want to redirect the log statements to file instead of console.

我使用这种方法,但它导致控制台和文件中的日志。

I have used this method but it results logging in Console as well as in file.

- (BOOL)redirectNSLog
{
    // Create log file
    [@"" writeToFile:@"/NSLog.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
    id fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/NSLog.txt"];
    if (!fileHandle)    return NSLog(@"Opening log failed"), NO;
    [fileHandle retain];

    // Redirect stderr
    int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
    if (!err)   return  NSLog(@"Couldn't redirect stderr"), NO;

    return  YES;
}

有可能在控制台中没有日志语句,

Is it possible to not have log statement in console but only in file ??

使用NSLog 登录控制台。您需要定义自己的函数 MyLog 或任何,并将 NSLog 的所有出现替换为 MyLog

NSLog is made to log into the console. You need to define your own function MyLog or whatever, and replace all occurrences of NSLog into MyLog.