iOS崩溃检测记录方案.md

崩溃日志方案

任何一个app,崩溃都是无法容忍而又无法杜绝的现实。所以在崩溃的时候能够及时检测到原因尤为重要。

监控崩溃方案

在app再次启动后,进行崩溃信号监听。

void UncaughtExceptionHandler(NSException *exception) {
  NSArray *callStackSymbols = [exception callStackSymbols];
  NSArray *callStackReturnAddresses = [exception callStackReturnAddresses];
  NSString *name = [exception name];
  NSString *reason = [exception reason];
  NSDictionary *userInfo = [exception userInfo];
}

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

使用上述方法NSSetUncaughtExceptionHandler()可以在崩溃的时候捕获到崩溃原因,响应的栈信息等。
将设备信息和崩溃信息保存在本地,因为在此之后App就会闪退,所以只能做很少的操作。

+ (void)saveCrashFileToLocalWithInfo:(NSString *)crashInfo {
  UIDevice *device = [UIDevice currentDevice];
  NSString *deviceInfo = [NSString stringWithFormat:@"%@,%@%@", device.model, device.systemName, device.systemVersion];
  NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  dict[@"crashInfo"] = crashInfo;
  dict[@"time"] = [NSDate.date stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
  dict[@"sys"] = deviceInfo;
  NSString *filePath = [self localFilePath];
  [dict writeToFile:filePath atomically:YES];
}

保存的时候同时可以附加上崩溃的时间点、设备信息等。
当app再次打开后,获取本地保存的崩溃信息并上传到服务器即可。

+ (void)uploadCrashInfoToServer {
    NSString *crashInfo = [self localSavingCrashInfo];
    if ([crashInfo length]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // send request
        });
    }
}

测试打印的数据如下:

> Crash Time
2020-05-27 11:35:49
> Device Info
iPhone,iOS13.4.1
> Crash Info
>> name:
NSInvalidArgumentException
>> reason:
*** -[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: a)
>> callStackSymbols:
(
  0   CoreFoundation      0x000000018d8f4178 9624AAFD-5437-3772-A507-0F357875808D + 1253752
  1   libobjc.A.dylib     0x000000018d608c1c objc_exception_throw + 60
  2   CoreFoundation      0x000000018d94d3a8 9624AAFD-5437-3772-A507-0F357875808D + 1618856
  3   CoreFoundation      0x000000018d957524 9624AAFD-5437-3772-A507-0F357875808D + 1660196
  4   CoreFoundation      0x000000018d7c9400 9624AAFD-5437-3772-A507-0F357875808D + 29696
  5   ZZDemos             0x00000001000183b0 __20-[ZZBuglyVC makeBug]_block_invoke_4 + 128
  6   UIKitCore           0x000000019102b178 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 369016
…
)

你可能感兴趣的:(iOS崩溃检测记录方案.md)