[英]iPhone: Once I have redirected NSLog to a file, how do I revert it to the console?
我正在使用:
#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
..将NSLog重定向到一个文件,该文件偶然工作得很好。
我想进行日志记录以归档一些文件,我的应用程序的用户可以打开和关闭..那么,有人知道我如何将NSLog / stderr重定向回控制台吗?
谢谢!
这取自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");
这并没有明确回答您的问题,但是如果您需要重定向的只是NSLog的输出,那么我会考虑在NSLog()周围使用包装器,并根据标记确定是否要发送到文件还是常规NSLog / stderr您保持用户可以控制的范围。
(对我来说,从根本上重定向stderr流以实现此目标是一个令人惊讶的设计,并且使用NSLog级别之上的包装器,您可以根据需要轻松地选择将输出发送到两个地方。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.