iOS 将NSLog写入文件中

2019-03-12  本文已影响0人  小明讲啥故事

写在AppDelegate.m的** application: didFinishLaunchingWithOptions**中:

#if (DEBUG == 1 || TARGET_OS_SIMULATOR)
#else
#ifdef FILELOG_SUPPORT
    [self redirectNSlogToDocumentFolder];
#endif
#endif
#pragma mark 日志记录方法
- (void)redirectNSLogToDocumentFolder {

   UIDevice *device = [UIDevice currentDevice];
    if([[device model] hasSuffix:@"Simulator"]) { //在模拟器不保存到文件中
        return;
    }
    
    //将NSlog打印信息保存到Document目录下的Log文件夹下
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:logDirectory];
    if (!fileExists) {
        [fileManager createDirectoryAtPath:logDirectory  withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //每次启动后都保存一个新的日志文件中
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSString *logFilePath = [logDirectory stringByAppendingFormat:@"/%@.log",dateStr];
    //将log输入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
    
    //删除今天以前的数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *ToDayTimeStr = [formatter stringFromDate:[NSDate date]];
        NSDate *ToDayDate = [formatter dateFromString:ToDayTimeStr];
        NSArray *fileListArr = [fileManager contentsOfDirectoryAtPath:logDirectory error:nil];
        for (NSString *Str in fileListArr) {
            NSString *DayTimeInStr = [Str substringToIndex:10];
            NSDate *OtherDate = [formatter dateFromString:DayTimeInStr];
            NSComparisonResult result = [ToDayDate compare:OtherDate];
            if (result == NSOrderedDescending) {
                NSFileManager *fileManger = [NSFileManager defaultManager];
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"];
                NSString *filePath = [logDirectory stringByAppendingPathComponent:Str];
                [fileManger removeItemAtPath:filePath error:nil];
            }
        }
    });
}
上一篇 下一篇

猜你喜欢

热点阅读