iPhone:一旦我将NSLog重定向到文件,我该如何将其还原到控制台?

Ben*_*ton 8 iphone logging file nslog freopen

我正在使用:

#if TARGET_IPHONE_SIMULATOR == 0
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"];
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
#endif
Run Code Online (Sandbox Code Playgroud)

..将NSLog重定向到一个文件,这个文件很有用.

我想记录文件,我的应用程序的用户可以打开和关闭..所以有谁知道如何将NSLog/stderr重定向控制台?

谢谢!

小智 16

这取自 http://www.atomicbird.com/blog/2007/07/code-quickie-redirect-nslog

// Save stderr so it can be restored.
int stderrSave = dup(STDERR_FILENO);

// Send stderr to our file
FILE *newStderr = freopen("/tmp/redirect.log", "a", stderr);

NSLog(@"This goes to the file");

// Flush before restoring stderr
fflush(stderr);

// Now restore stderr, so new output goes to console.
dup2(stderrSave, STDERR_FILENO);
close(stderrSave);

// This NSLog will go to the console.
NSLog(@"This goes to the console");
Run Code Online (Sandbox Code Playgroud)


Ben*_*tto 4

这并没有明确回答您的问题,但如果您需要重定向的是 NSLog 的输出,那么我会考虑使用 NSLog() 周围的包装器,并根据以下标志决定是发送到文件还是发送到常规 NSLog/stderr您保留用户可以控制的内容。

(对我来说,从根本上重定向 stderr 流来完成此操作是一个令人惊讶的设计 - 并且使用 NSLog 级别之上的包装器,如果您愿意,您可以轻松选择将输出发送到这两个地方。)