照例先上github地址
做这个的原因
程序测试时并不是总是连着Xcode的,这就导致如果测试过程中程序出现崩溃时,可能是由于数据异常引起的,而我们有无法看到数据,连接Xcode重测时,有时候问题并不能重现,导致很多问题无法确认,所以想把所有NSLog输出的数据,保存到文件中。这样,当程序出问题时,我们只需导出log文件,查看,便可很容易的复现问题。
用法
- 如果想要NSLog输出的内容和崩溃信息都放入日志文件中,就在application:didFinishLaunchingWithOptions:方法中实现方法redirectNSLogToDocumentFolder
- 如果只是想要保存崩溃信息到日志文件中,只需在application:didFinishLaunchingWithOptions:方法中实现NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);就可以了。
保持淡定, 人生从此不再寂寞。(其实,这只是个分割线,哈哈)
文笔不好,还是直接上代码
- (void)redirectNSLogToDocumentFolder
{
//如果已经连接Xcode调试则不输出到文件
if (isatty(STDOUT_FILENO)) {
return;
}
//判定如果是模拟器就不输出
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) {
NSError *error = nil;
[fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"error = %@",[error localizedDescription]);
}
}
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);
//捕获Object-C异常日志
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
}
void UncaughtExceptionHandler(NSException* exception)
{
NSString *name = [exception name];
NSString *reason = [exception reason];
NSArray *symbols = [exception callStackSymbols];
//异常发生时的调用栈
NSMutableString *strSymbols = [[NSMutableString alloc]init];
//将调用栈平成输出日志的字符串
for (NSString *str in symbols) {
[strSymbols appendString:str];
[strSymbols appendString:@"\r\n"];
}
//将crash日志保存到Document目录下的Log文件夹下
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *logDirectory = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Log"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:logDirectory]) {
NSError *error = nil;
[fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"error = %@",[error localizedDescription]);
}
}
NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
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 *crashString = [NSString stringWithFormat:@",- %@ ->[Uncaught Exception]\r\nName:%@,Reason:%@\r\n[Fe Symbols Start]\r\n%@[Fe Symbols End]\r\n\r\n",dateStr,name,reason,strSymbols];
//把错误日志写到文件中
if (![fileManager fileExistsAtPath:logFilePath]) {
[crashString writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}else{
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
[outFile seekToEndOfFile];
[outFile writeData:[crashString dataUsingEncoding:NSUTF8StringEncoding]];
[outFile closeFile];
}
//把错误日志发送到邮箱
NSString *urlStr = [NSString stringWithFormat:@"mailto://(此处为邮箱地址)?subject=bug&body=感谢您的配合错误详情:%@",crashString];
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication]openURL:url];
}
注:这段代码写的挺早了,参考链接已找不到,不能贴出来,但仍要感谢。