美文网首页OC进化iOS Developer
iOS - crash日志抓取保存

iOS - crash日志抓取保存

作者: Codepgq | 来源:发表于2016-11-28 17:16 被阅读1174次
  • 前言

曾经我以为我的程序可以一帆风顺,知道我们遇到了你-crash,那是一段令人呕吐的回忆。

  • 背景

  • 在实际项目开发中,我们会遇到很多不同的问题,有写嘛随着编程经验丰富,随手就可以解决了,但是如果你的程序以及发布到商店了,并且已经通过审核,某天某个客户反馈:“你这个是个什么XX%%XX%%,辣鸡,闪退”;又或者把程序给测试人员了,那边反应闪退了,but 没有现场,不知道原因,排查起来那也是一件很忧伤的事情。

  • 结论

  • 综上所述,我们还是有必要写一个抓取奔溃信息的东东的:
    第一:能让你的程序越来越强壮
    第二:能在一定程度上让你快速修复BUG
    第三:能让你知道你踏了哪些坑
    第四:还能和测试妹子多沟通不是(你把手机拿过来哦,我来看看log信息,然后测试妹子就来了……咳~正经一点,我们是讨论技术的)

好在Apple已经提供了方法给我们了,不然又得让吃螃蟹的人死多少脑细胞。

<br />

个人拙见

这个是系统定义的一个方法,让我们传入一个方法地址(不能乱写的),当程序奔溃了就会触发这个方法,不仅仅可以用来获取log信息,还可以保存一下数据。

typedef void NSUncaughtExceptionHandler(NSException *exception);

FOUNDATION_EXPORT NSUncaughtExceptionHandler * _Nullable NSGetUncaughtExceptionHandler(void);
FOUNDATION_EXPORT void NSSetUncaughtExceptionHandler(NSUncaughtExceptionHandler * _Nullable);

<br />
为了能不在AppDelegate中写那么多冗余的代码,于是我把他稍微的封装了一下

1、先导入头文件

#import "PQCatchErrorLog.h"

<br />

2、“注册”抓取Log

这里之所以用双引号因为我也不知道怎么去描述,
但是和通知很像,当发送奔溃时才会通知,所以这里就相当于注册通知,大家仁者见仁智者见智。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [PQCatchErrorLog catchLog];
    
    [PQCatchErrorLog printErrorLog];
    
    return YES;
}

3、...

然后?然后就没了……
此外还提供了

/**
 得到LOG信息

 @return log信息 - NSString
 */
+ (NSString *)logInfo;


/**
 得到LOG信息,以便于上传

 @return log信息 - Data
 */
+ (NSData *)logData;


/**
 删除error信息

 @return 返回是否删除成功
 */
+ (BOOL)delErrorLogFile;

对应的实现代码

+ (void)catchLog{
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        //捕捉崩溃信息
        NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
    }
    return self;
}


+ (void)printErrorLog{
    NSLog(@"path - %@ \nerrorLog - %@",LOGFilePath,[PQCatchErrorLog logInfo]);
}

+ (NSString *)logInfo{
    return [NSString stringWithContentsOfFile:LOGFilePath encoding:NSUTF8StringEncoding error:nil];
}

+ (NSData *)logData{
    return [[PQCatchErrorLog logInfo] dataUsingEncoding:NSUTF8StringEncoding];
}

+ (BOOL)delErrorLogFile{
    NSError * error;
    [[NSFileManager defaultManager] removeItemAtPath:LOGFilePath error:&error];
    
    if (!error) {
        return YES;
    }
    
    NSLog(@"\n删除失败 - %@",error);
    return NO;
}

<br />

并且为了记录时间,我还写了一个类别方法,一起写在了类中

.h
// ----------------   把时间转化为字符串     -----------------
@interface NSDate (PQCatchErrorLog)
/**
 把当前时间转化字符串
 
 @return 当前时间字符串
 */
+ (NSString *)currentDateForDateSeconds;
@end

.m
/**
 把当前时间转化字符串
 
 @return 当前时间字符串
 */
+ (NSString *)currentDateForDateSeconds{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *destDateString1 = [dateFormatter stringFromDate:[NSDate date]];
    NSString *destDateString = [destDateString1 substringFromIndex:2];
    return destDateString;
}

<br />

还有一个地址拼接的

.h
// ----------------   文件地址拼接     -----------------
@interface NSString (PQCatchErrorLog)
/**
 为字符串添加地址
 
 @return 地址
 */
- (NSString *)byAppendToCacheDocument;
@end


.m
/**
 为字符串添加地址
 
 @return 地址
 */
- (NSString *)byAppendToCacheDocument{
    NSString * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    return [path stringByAppendingPathComponent:self];
}

<br />
<br /><br />

最后在介绍一下:如何保存log信息

//抓取奔溃日志
void UncaughtExceptionHandler(NSException *exception) {
    
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    
    NSString *reason = [exception reason];//非常重要,就是崩溃的原因
    
    NSString *name = [exception name];//异常类型
    
    NSMutableString * log = [NSMutableString stringWithFormat:@"callStackSymbols - 当前栈信息:\n"];
    for (NSString * str in arr) {
        [log appendFormat:@"%@\n",str];
    }
    [log appendFormat:@"\nreason - 崩溃原因:\n %@",reason];
    [log appendFormat:@"\nname - 异常类型:\n %@",name];
    
    [log insertString:[NSString stringWithFormat:@"*************** %@ *******************\n",[NSDate currentDateForDateSeconds]] atIndex:0];
    
    //创建一个文件 如果是第一次就直接写入,然后返回
    if (![[NSFileManager defaultManager]fileExistsAtPath:LOGFilePath]) {
        [[NSFileManager defaultManager]createFileAtPath:LOGFilePath contents:nil attributes:nil];
        [log insertString:[NSString stringWithFormat:@"\n*************** 奔溃日志 *******************\n"] atIndex:0];
        [log writeToFile:LOGFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        return;
    }
    
    //创建一个fileHandler
    NSFileHandle * fileHandler = [NSFileHandle fileHandleForWritingAtPath:LOGFilePath];
    //跳到文件末尾
    [fileHandler seekToEndOfFile];
    //写入文件
    [fileHandler writeData:[log dataUsingEncoding:NSUTF8StringEncoding]];
    //关闭file Handler
    [fileHandler closeFile];
}

最后故意在ViewController中写了一个数组越界的BUG
大家自行感受一下:

*************** 奔溃日志 *******************
*************** 16-11-28 15:32:47 *******************
callStackSymbols - 当前栈信息:
0   CoreFoundation                      0x000000010c91634b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x000000010c37721e objc_exception_throw + 48
2   CoreFoundation                      0x000000010c96ebdf -[__NSSingleObjectArrayI objectAtIndex:] + 111
3   CatchErrorLog抓取奔溃信息     0x000000010bda22a3 -[ViewController viewDidLoad] + 163
4   UIKit                               0x000000010cedac99 -[UIViewController loadViewIfRequired] + 1258
5   UIKit                               0x000000010cedb0cc -[UIViewController view] + 27
6   UIKit                               0x000000010cda4c51 -[UIWindow addRootViewControllerViewIfPossible] + 71
7   UIKit                               0x000000010cda53a2 -[UIWindow _setHidden:forced:] + 293
8   UIKit                               0x000000010cdb8cb5 -[UIWindow makeKeyAndVisible] + 42
9   UIKit                               0x000000010cd31c89 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4818
10  UIKit                               0x000000010cd37de9 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1731
11  UIKit                               0x000000010cd34f69 -[UIApplication workspaceDidEndTransaction:] + 188
12  FrontBoardServices                  0x000000010fe87723 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
13  FrontBoardServices                  0x000000010fe8759c -[FBSSerialQueue _performNext] + 189
14  FrontBoardServices                  0x000000010fe87925 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
15  CoreFoundation                      0x000000010c8bb311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16  CoreFoundation                      0x000000010c8a059c __CFRunLoopDoSources0 + 556
17  CoreFoundation                      0x000000010c89fa86 __CFRunLoopRun + 918
18  CoreFoundation                      0x000000010c89f494 CFRunLoopRunSpecific + 420
19  UIKit                               0x000000010cd337e6 -[UIApplication _run] + 434
20  UIKit                               0x000000010cd39964 UIApplicationMain + 159
21  CatchErrorLog抓取奔溃信息     0x000000010bda280f main + 111
22  libdyld.dylib                       0x000000010f6f668d start + 1

reason - 崩溃原因:
 *** -[__NSSingleObjectArrayI objectAtIndex:]: index 2 beyond bounds [0 .. 0]
name - 异常类型:
 NSRangeException

在第3行:标出来了在哪个方法中

在第2行:标出来了是用数组取值

在崩溃原因中标出来了: 数组越界

最后一行是:异常类型

<br />

最后的最后
DEMO地址 如果有用,烦请star

相关文章

  • iOS - crash日志抓取保存

    前言 曾经我以为我的程序可以一帆风顺,知道我们遇到了你-crash,那是一段令人呕吐的回忆。 背景 在实际项目开发...

  • ios开发-崩溃分析

    崩溃日志 如何得到crash report 当一个iOS应用程序崩溃时, 系统会创建一份crash日志保存在设备上...

  • iOS 抓取crash日志

    前言在app开发过程中难免会遇到崩溃的问题, 在线下的环境我们可以通过断点找到崩溃的代码, 从而分析出问题的原因,...

  • ios抓取crash日志

    经常会闪退的异常哪些:数组越界、空引用、引用未定义方法、内存空间不足 1、使用XCode点击Window—Devi...

  • GT-IOS性能测试的集成工具

    简介 GT:对app进行性能测试、开发日志的查看、crash日志查看、网络数据包的抓取、代码耗时统计。支持iOS和...

  • 如何追踪app崩溃率,如何解决线上闪退

    当iOS设备上的App应用闪退时,操作系统会生成一个crash日志,保存在设备上。crash日志上有很多有用的信息...

  • App崩溃追踪,原因定位分析

    当iOS设备上的App应用闪退时,操作系统会生成一个crash日志,保存在设备上。crash日志上有很多有用的信息...

  • iOS 符号化闪退日志

    iOS分析崩溃日志 二 iOS应用崩溃日志分析 iOS崩溃crash大解析

  • iOS Crash问题

    本文就捕获iOS Crash、Crash日志组成、Crash日志符号化、异常信息解读、常见的Crash五部分介绍。...

  • crash

    iOS Crash文件的解析(一)教你如何对ios崩溃(crash)日志做符号化IOS本地日志记录解决方案友盟统计...

网友评论

    本文标题:iOS - crash日志抓取保存

    本文链接:https://www.haomeiwen.com/subject/rmpopttx.html