NSLog重定向

2017-04-12  本文已影响180人  LeafRead

//实现下面的方法完成NSLog重定向到文件

- (void)redirectNSLogToDucumentFile{

//创建文件路径

NSString *documentpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *fileName = [NSString stringWithFormat:@"%@.log",[NSDate date]];

NSString *logFilePath = [documentpath stringByAppendingPathComponent:fileName];

//删除已经存在文件

NSLog(@"logFilePath---> %@",logFilePath);

NSFileManager *fileManager = [NSFileManager defaultManager];

[fileManager removeItemAtPath:logFilePath error:nil];

//log写入

freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);

}

一般我们都会在应用中放置一个开关,开启或者关闭Log日志的重定向,在上面,我们使用标准C的freopen将stderr重定向到我们的文件中了,那么问题来了,怎么重定向回去呢???

FILE * freopen (constchar* filename,constchar* mode, FILE * stream );

要想重定向回去,那么我们需要知道stderr原来的文件路径,很遗憾,这个在不同平台中是不一样的,在iOS平台,由于沙盒机制,我们也并不能直接使用沙盒外的文件 对此,freopen将无能为力,要重定向回去,只能使用Unix的方法dup和dup2!

//在ios上可用的方式,还是得借助dup和dup2intoriginH1 = dup(STDERR_FILENO);

FILE * myFile = freopen([loggingPath cStringUsingEncoding:NSASCIIStringEncoding],"a+", stderr);//这句话已经重定向了,现在NSLog都输出到文件中去了,//……………….//恢复原来的dup2(originH1, STDERR_FILENO);//就可以了

恢复重定向摘录:https://yohunl.com/iosri-zhi-huo-qu-he-shi-shi-liu-lan-qi-xian-shi-ri-zhi/

上一篇 下一篇

猜你喜欢

热点阅读