ios nslog 例子_iOS 将NSLog写入到文件中

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

#if (DEBUG == 1 || TARGET_OS_SIMULATOR)

#else

#ifdef FILELOG_SUPPORT

[self redirectNSlogToDocumentFolder];

#endif

#endif```

// 将NSlog打印信息保存到Document目录下的文件中

(void)redirectNSlogToDocumentFolder

{

//document文件夹

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentDirectory = [paths objectAtIndex:0];

//

NSString *foldPath = [documentDirectory stringByAppendingFormat:@"/appLog"];

//文件保护等级

NSDictionary *attribute = [NSDictionary dictionaryWithObject:NSFileProtectionNone

forKey:NSFileProtectionKey];

[[NSFileManager defaultManager] createDirectoryAtPath:foldPath withIntermediateDirectories:YES attributes:attribute 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 = [foldPath stringByAppendingFormat:@"/%@.log",dateStr];

[Utils checkFlieProtection:logFilePath];

// 将log输入到文件

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

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

}

pragma mark -File Handel

(void)checkFlieProtection:(NSString *)path {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *pathSqlite = path;

NSDictionary *attributeSql = [fileManager attributesOfItemAtPath:pathSqlite error:nil];

if ([[attributeSql objectForKey:NSFileProtectionKey] isEqualToString:NSFileProtectionComplete]) {

NSDictionary *attribute = [NSDictionary dictionaryWithObject:NSFileProtectionCompleteUntilFirstUserAuthentication

forKey:NSFileProtectionKey];

[fileManager setAttributes:attribute ofItemAtPath:pathSqlite error:nil];

NSLog(@"改变文件权限 %@ : %@",path,attribute);

}

}

### Tips

- 文件保护等级属性列表

NSFileProtectionNone //文件未受保护,随时可以访问 (Default)

NSFileProtectionComplete //文件受到保护,而且只有在设备未被锁定时才可访问

NSFileProtectionCompleteUntilFirstUserAuthentication //文件收到保护,直到设备启动且用户第一次输入密码

NSFileProtectionCompleteUnlessOpen //文件受到保护,而且只有在设备未被锁定时才可打开,不过即便在设备被锁定时,已经打开的文件还是可以继续使用和写入

- freopen

[freopen()函数](http://c.biancheng.net/cpp/html/2508.html)用于文件流的的重定向,一般是将 stdin、stdout 和 stderr 重定向到文件。

所谓重定向,就是改变文件流的源头或目的地。stdout(标准输出流)的目的地是显示器,printf()是将流中的内容输出到显示器;可以通过freopen()将stdout 的目的地改为一个文件(如output.txt),再调用 printf(),就会将内容输出到这个文件里面,而不是显示器。 freopen()函数的原型为: FILE *freopen(char *filename, char *type, FILE *stream);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值