对于mac开发者来说,进行日志收集和上传尤为重要,没有日志就无法进行分析问题。通常来说我们会将日志文件.log存在
~/library/logs/YourAppName
的目录下,大部分app都是这样放置的,然后缓存文件存在
~/library/Caches/YourAppName
目录下。
简单的日志存储
使用stdout重定向来将控制台的日志写入日志文件.log中,从而达到日志存储的目的
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
通常来说,日志文件名称需要加上日志以及app名等相关信息,以便于筛选。
- (void)redirectNSlogToDocumentFolder{
//这里判断是否连接xcode,如果连接xcode我们更希望是输出到控制台,这样我们能更能直接进行调试
#if DEBUG
#else
if (isatty(STDOUT_FILENO)){
NSLog(@"Appdelegate redirectNSlogToDocumentFolder failed : connected xcode mode");
return;
}
#endif
NSString *genseePath = [self mylogPath];
NSFileManager* manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath:genseePath withIntermediateDirectories:NO attributes:NULL error:NULL];
NSString* bundleName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
NSString* bundleID = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//这里使用的日期格式为 yyyyMMdd-HHmmss
[dateFormatter setDateFormat:@"yyyyMMdd-HHmmss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@_%@_%@.log",bundleName,bundleID,dateString];
_logPath = fileName;
NSString *logFilePath = [genseePath stringByAppendingPathComponent:fileName];
NSLog(@"[Appdelegate] redirectNSlog