打印日志信息到文件

在真机,或真机没连接到电脑时,可以把日志信息输出到文件

1.设置日志文件路径

 1 - (NSString*)logFilePath {
2 //非越狱版路径
3 #ifndef CRACK
4 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
5 NSString *documentsDirectory = [paths objectAtIndex:0];
6 //越狱版路径
7 #else
8 NSString *documentsDirectory = @"/var/root/Media/xiaodao/";
9 #endif
10 NSString *logDir = [documentsDirectory stringByAppendingPathComponent:@"logs"];
11 BOOL isDir = YES;
12 //如果logs文件夹存不存在,则创建
13 if([[NSFileManager defaultManager] fileExistsAtPath:logDir isDirectory:&isDir] == NO)
14 {
15 [[NSFileManager defaultManager] createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil];
16 }
17 //以当天的时间为文件名,文件名后缀为.log
18 NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
19 NSString *logPath = [logDir stringByAppendingPathComponent:fileName];
20 return logPath;
21 }

2.开始打印日志

1 - (void)startLog {
2 freopen([[self logFilePath] cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
3 }

freopen重定向打印

stderr为标准出错信息

3.关闭打印日志

1 - (void)finishLog { 
2 fflush(stderr);
3 dup2(dup(STDERR_FILENO), STDERR_FILENO);
4 close(dup(STDERR_FILENO));
5 }

4.清空日志文件

1 - (BOOL)deleteLogFile {
2 BOOL success = [[NSFileManager defaultManager] removeItemAtPath:[self logFilePath] error:nil];
3 return success;
4 }





 

posted @ 2012-02-14 14:54  月光的尽头  阅读(1906)  评论(0编辑  收藏  举报