崩潰日志方案
任何一個app,崩潰都是無法容忍而又無法杜絕的現(xiàn)實珠十。所以在崩潰的時候能夠及時檢測到原因尤為重要焙蹭。
監(jiān)控崩潰方案
在app再次啟動后,進行崩潰信號監(jiān)聽桐智。
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()可以在崩潰的時候捕獲到崩潰原因烟馅,響應(yīng)的棧信息等。
將設(shè)備信息和崩潰信息保存在本地郑趁,因為在此之后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];
}
保存的時候同時可以附加上崩潰的時間點躲惰、設(shè)備信息等变抽。
當(dāng)app再次打開后,獲取本地保存的崩潰信息并上傳到服務(wù)器即可诡宗。
+ (void)uploadCrashInfoToServer {
NSString *crashInfo = [self localSavingCrashInfo];
if ([crashInfo length]) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// send request
});
}
}
測試打印的數(shù)據(jù)如下:
> 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
…
)