ToB企服应用市场:ToB评测及商务社交产业平台

标题: iOS全埋点解决方案-采集崩溃 [打印本页]

作者: 没腿的鸟    时间: 2022-6-20 14:51
标题: iOS全埋点解决方案-采集崩溃
前言

​        采集应用程序崩溃信息,主要分为以下两种场景:
一、NSException 异常

​        NSException 异常是 Objective-C 代码抛出的异常。在 iOS 应用程序中,最常见就是通过 @throw 抛出的异常。比如,常见的数组越界访问异常。
1.1 捕获 NSException

​        我们可以通过 NSSetUNcaughtExceptionHandle 函数来全局设置异常处理函数,然后手机异常堆栈信息并触发响应的事件($AppCrashed),来实现 NSException 异常的全埋点。
第一步:在 SensorsSDK 项目中创建 SensorsAnalyticsExtensionHandler 类,并增加 + sharedInstance 方法并实现
  1. #import <Foundation/Foundation.h>
  2. NS_ASSUME_NONNULL_BEGIN
  3. @interface SensorsAnalyticsExtensionHandler : NSObject
  4. + (instancetype)sharedInstance;
  5. @end
  6. NS_ASSUME_NONNULL_END
复制代码
  1. @implementation SensorsAnalyticsExtensionHandler
  2. + (instancetype)sharedInstance {
  3.     static SensorsAnalyticsExtensionHandler *instance = nil;
  4.     static dispatch_once_t onceToken;
  5.     dispatch_once(&onceToken, ^{
  6.         instance = [[SensorsAnalyticsExtensionHandler alloc] init];
  7.     });
  8.     return instance;
  9. }
  10. @end
复制代码
第二步:实现 -init ,并通过 NSSetUncaughtExceptionHandler 函数全局设置异常处理函数,然后再全局处理函数中采集异常信息,并触发 $AppCrashed 事件。其中,异常的堆栈信息会放到 $app_crashed_reason 事件属性中。
  1. //
  2. //  SensorsAnalyticsExtensionHandler.m
  3. //  SensorsSDK
  4. //
  5. //  Created by renhao on 2022/4/22.
  6. //
  7. #import "SensorsAnalyticsExtensionHandler.h"
  8. #import "SensorsAnalyticsSDK.h"
  9. @implementation SensorsAnalyticsExtensionHandler
  10. + (instancetype)sharedInstance {
  11.     static SensorsAnalyticsExtensionHandler *instance = nil;
  12.     static dispatch_once_t onceToken;
  13.     dispatch_once(&onceToken, ^{
  14.         instance = [[SensorsAnalyticsExtensionHandler alloc] init];
  15.     });
  16.     return instance;
  17. }
  18. - (instancetype)init {
  19.     self = [super init];
  20.     if (self) {
  21.         NSSetUncaughtExceptionHandler(&sensorsdata_uncaught_excepting_handler);
  22.     }
  23.     return self;
  24. }
  25. static void sensorsdata_uncaught_excepting_handler(NSException *exception) {
  26.     // 采集 $AppCrashec 事件
  27.     [[SensorsAnalyticsExtensionHandler sharedInstance] trackAppCrashedWithException:exception];
  28. }
  29. - (void)trackAppCrashedWithException:(NSException *)exception {
  30.     NSMutableDictionary *properties = [NSMutableDictionary dictionary];
  31.     // 异常名称
  32.     NSString *name = [exception name];
  33.     // 出现异常的原因
  34.     NSString *reason = [exception reason];
  35.     // 异常的堆栈信息
  36.     NSArray *stacks = [exception callStackSymbols];
  37.     // 将异常信息组装
  38.     NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
  39.     properties[@"$app_crashed_reason"] = exceptionInfo;
  40.     [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
  41.    
  42.     NSSetUncaughtExceptionHandler(NULL);
  43. }
  44. @end
复制代码
第三步:在 SensorsAnalyticsSDK 的 - initWithServerURL: 方法中初始化 SensorsAnalyticsExtensionHandler 的单例对象
  1. #import "SensorsAnalyticsExtensionHandler.h"
  2. - (instancetype)initWithServerURL:(NSString *)urlString {
  3.     self = [super init];
  4.     if (self) {
  5.         _automaticProperties = [self collectAutomaticProperties];
  6.         // 设置是否需是被动启动标记
  7.         _launchedPassively = UIApplication.sharedApplication.backgroundTimeRemaining != UIApplicationBackgroundFetchIntervalNever;
  8.         
  9.         _loginId = [[NSUserDefaults standardUserDefaults] objectForKey:SensorsAnalyticsLoginId];
  10.         
  11.         _trackTimer = [NSMutableDictionary dictionary];
  12.         
  13.         _enterBackgroundTrackTimerEvents = [NSMutableArray array];
  14.         
  15.         _fileStroe = [[SensorsAnalyticsFileStore alloc] init];
  16.         
  17.         _database = [[SensorsAnalyticsDatabase alloc] init];
  18.         
  19.         _network = [[SensorsAnalyticsNetwork alloc] initWithServerURL:[NSURL URLWithString:urlString]];
  20.         
  21.         NSString *queueLabel = [NSString stringWithFormat:@"cn.sensorsdata.%@.%p", self.class, self];
  22.         _serialQueue = dispatch_queue_create(queueLabel.UTF8String, DISPATCH_QUEUE_SERIAL);
  23.         
  24.         _flushBulkSize = 100;
  25.         
  26.         _flushInterval = 15;
  27.         
  28.         [SensorsAnalyticsExtensionHandler sharedInstance];
  29.         
  30.         // 添加应用程序状态监听
  31.         [self setupListeners];
  32.         
  33.         [self startFlushTimer];
  34.     }
  35.     return self;
  36. }
复制代码
第四步:测试验证
  1.         NSArray *array = @[@"first"];
  2.         NSLog(@"%@", array[1]);
复制代码
  1. {
  2.   "propeerties" : {
  3.     "$model" : "arm64",
  4.     "$manufacturer" : "Apple",
  5.     "$app_crashed_reason" : "Exception name: NSRangeException\n Exception reason: *** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]\n Exception stack: (\n\t0   CoreFoundation                      0x00000001803f25e4 __exceptionPreprocess + 236\n\t1   libobjc.A.dylib                     0x000000018019813c objc_exception_throw + 56\n\t2   CoreFoundation                      0x000000018043da14 -[__NSSingleObjectArrayI getObjects:range:] + 0\n\t3   Demo                                0x0000000100b0bbc0 -[ViewController tableView:didSelectRowAtIndexPath:] + 696\n\t4   CoreFoundation                      0x00000001803f8aa0 __invoking___ + 144\n\t5   CoreFoundation                      0x00000001803f5fc8 -[NSInvocation invoke] + 300\n\t6   CoreFoundation                      0x00000001803f6288 -[NSInvocation invokeWithTarget:] + 76\n\t7   SensorsSDK                      libc++abi: terminating with uncaught exception of type NSException
  6.     0x0000000100ea9210 -[SensorsAnalyticsDelegateProxy forwardInvocation:] + 96\n\t8   CoreFoundation                      0x00000001803f6594 ___forwarding___ + 736\n\t9   CoreFoundation                      0x00000001803f88ec _CF_forwarding_prep_0 + 92\n\t10  UIKitCore                           0x0000000184fa79a4 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:isCellMultiSelect:deselectPrevious:] + 1620\n\t11  UIKitCore                           0x0000000184fa7338 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 112\n\t12  UIKitCore                           0x0000000184fa7c20 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 316\n\t13  UIKitCore                           0x0000000185287568 -[_UIAfterCACommitBlock run] + 64\n\t14  UIKitCore                           0x0000000185287a3c -[_UIAfterCACommitQueue flush] + 188\n\t15  libdispatch.dylib                   0x00000001010f433c _dispatch_call_block_and_release + 24\n\t16  libdispatch.dylib                   0x00000001010f5b94 _dispatch_client_callout + 16\n\t17  libdispatch.dylib                   0x0000000101104650 _dispatch_main_queue_drain + 1064\n\t18  libdispatch.dylib                   0x0000000101104218 _dispatch_main_queue_callback_4CF + 40\n\t19  CoreFoundation                      0x0000000180360218 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12\n\t20  CoreFoundation                      0x000000018035a69c __CFRunLoopRun + 2432\n\t21  CoreFoundation                      0x0000000180359804 CFRunLoopRunSpecific + 572\n\t22  GraphicsServices                    0x000000018c23660c GSEventRunModal + 160\n\t23  UIKitCore                           0x0000000184d7bd2c -[UIApplication _run] + 992\n\t24  UIKitCore                           0x0000000184d808c8 UIApplicationMain + 112\n\t25  Demo                                0x0000000100b0c334 main + 128\n\t26  dyld                                0x0000000100df5cd8 start_sim + 20\n\t27  ???                                 0x0000000100b3d0f4 0x0 + 4306751732\n\t28  ???                                 0xac3c800000000000 0x0 + 12410935410614599680\n)",
  7.     "$lib_version" : "1.0.0",
  8.     "$os" : "iOS",
  9.     "$app_version" : "1.0",
  10.     "$os_version" : "15.4",
  11.     "$lib" : "iOS"
  12.   },
  13.   "event" : "$AppCrashed",
  14.   "time" : 1650616086146,
  15.   "distinct_id" : "3E0DD30F-4F2F-425C-8323-FA43C149CE27"
  16. }
复制代码
1.2 传递 UncaughtExceptionHandler

​        问题描述:在应用程序实际开发过程中,可能会采集多个 SDK,如果这些 SDK 都按照上面介绍的方法采集异常信息,总会有一些 SDK 采集不到异常信息。这是因为通过 NSSetUncaughtExceptionHandler 函数设置的是一个全局异常处理函数,后面设置的异常处理函数会自动覆盖前面设置的异常处理函数。
​        解决方法:在调用 NSSetUncaughtExceptionHandler 函数设置全局异常处理函数前,先通过 NSGetUncaughtExceptionHandler 函数获取之前已设置的异常处理函数并保存,在处理完异常信息采集后,再主动调用已备份的处理函数(让所有的异常处理函数形成链条),即可解决上面提到的覆盖问题。
  1. #import "SensorsAnalyticsExtensionHandler.h"
  2. #import "SensorsAnalyticsSDK.h"
  3. @interface SensorsAnalyticsExtensionHandler()
  4. /// 保存之前已设置的异常处理函数
  5. @property (nonatomic) NSUncaughtExceptionHandler *previousExceptionHandler;
  6. @end
  7. @implementation SensorsAnalyticsExtensionHandler
  8. + (instancetype)sharedInstance {
  9.     static SensorsAnalyticsExtensionHandler *instance = nil;
  10.     static dispatch_once_t onceToken;
  11.     dispatch_once(&onceToken, ^{
  12.         instance = [[SensorsAnalyticsExtensionHandler alloc] init];
  13.     });
  14.     return instance;
  15. }
  16. - (instancetype)init {
  17.     self = [super init];
  18.     if (self) {
  19.         _previousExceptionHandler = NSGetUncaughtExceptionHandler();
  20.         NSSetUncaughtExceptionHandler(&sensorsdata_uncaught_excepting_handler);
  21.     }
  22.     return self;
  23. }
  24. static void sensorsdata_uncaught_excepting_handler(NSException *exception) {
  25.     // 采集 $AppCrashec 事件
  26.     [[SensorsAnalyticsExtensionHandler sharedInstance] trackAppCrashedWithException:exception];
  27.     NSUncaughtExceptionHandler *handle = [SensorsAnalyticsExtensionHandler sharedInstance].previousExceptionHandler;
  28.     if (handle) {
  29.         handle(exception);
  30.     }
  31. }
  32. - (void)trackAppCrashedWithException:(NSException *)exception {
  33.     NSMutableDictionary *properties = [NSMutableDictionary dictionary];
  34.     // 异常名称
  35.     NSString *name = [exception name];
  36.     // 出现异常的原因
  37.     NSString *reason = [exception reason];
  38.     // 异常的堆栈信息
  39.     NSArray *stacks = [exception callStackSymbols];
  40.     // 将异常信息组装
  41.     NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
  42.     properties[@"$app_crashed_reason"] = exceptionInfo;
  43.     [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
  44.    
  45.     NSSetUncaughtExceptionHandler(NULL);
  46. }
  47. @end
复制代码
二、捕获信号

2.1 Mach 异常和 Unix 信号

​        Mach 是 Mac OS 和 iOS 操作系统的微内核,Mach 异常就是最底层的内核级异常。在 iOS 系统中,每个 Thread、Task、Host 都有一个异常端口数据。开发者可以通过设置 Thread、Task、Host 的异常端口来捕获 Mach 异常。Mach 异常会被转换成相应的 Unix 信号,并传递给出错的线程。
2.2 捕获 Unix 信号异常

第一步:新增捕获 Unix 信号的处理函数
  1. static NSString * const SensorsDataSignalExceptionHandlerName = @"SignalExceptionHandler";
  2. static NSString * const SensorsDataSignalExceptionHandlerUserInfo = @"SignalExceptionHandlerUserIfo";
  3. static void sensorsdata_signal_exception_handler(int sig, struct __siginfo *info, void *context) {
  4.     NSDictionary *userInfo = @{SensorsDataSignalExceptionHandlerUserInfo: @(sig)};
  5.     NSString *reason = [NSString stringWithFormat:@"Signal %d was raised.", sig];
  6.     // 创建一个异常对象, 用于采集异常信息
  7.     NSException *exception = [NSException exceptionWithName:SensorsDataSignalExceptionHandlerName reason:reason userInfo:userInfo];
  8.    
  9.     SensorsAnalyticsExtensionHandler *handler = [SensorsAnalyticsExtensionHandler sharedInstance];
  10.     [handler trackAppCrashedWithException:exception];
  11. }
复制代码
第二步:在 - init 初始化方法中,注册信号处理函数
  1. - (instancetype)init {
  2.     self = [super init];
  3.     if (self) {
  4.         _previousExceptionHandler = NSGetUncaughtExceptionHandler();
  5.         NSSetUncaughtExceptionHandler(&sensorsdata_uncaught_excepting_handler);
  6.         
  7.         // 定义信号集结构体
  8.         struct sigaction sig;
  9.         // 将信号集初始化为空
  10.         sigemptyset(&sig.sa_mask);
  11.         // 在处理函数中传入__siginfo参数
  12.         sig.sa_flags = SA_SIGINFO;
  13.         // 设置信号集处理函数
  14.         sig.sa_sigaction = &sensorsdata_signal_exception_handler;
  15.         // 定义需要采集的信号类型
  16.         int signals[] = {SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV};
  17.         for(int i = 0; i < sizeof(signals) / sizeof(int); i++){
  18.             // 注册信号处理
  19.             int err = sigaction(signals[i], &sig, NULL);
  20.             if (err) {
  21.                 NSLog(@"Errored while trying to set up sigaction for signal %d", signals[i]);
  22.             }
  23.         }
  24.     }
  25.     return self;
  26. }
复制代码
第三步:修改 - trackAppCrashedWithException: 方法,当异常对象中没有堆栈信息时,就是默认获取当前线程的堆栈信息(由于 Unix 信息异常对象是我们自己构建的,因此并没有堆栈信息)
  1. - (void)trackAppCrashedWithException:(NSException *)exception {
  2.     NSMutableDictionary *properties = [NSMutableDictionary dictionary];
  3.     // 异常名称
  4.     NSString *name = [exception name];
  5.     // 出现异常的原因
  6.     NSString *reason = [exception reason];
  7.     // 异常的堆栈信息
  8.     NSArray *stacks = [exception callStackSymbols] ?: [NSThread callStackSymbols];
  9.     // 将异常信息组装
  10.     NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
  11.     properties[@"$app_crashed_reason"] = exceptionInfo;
  12.     [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
  13.    
  14.     // 获取 seasorsAnalyticsSDK 中的 serialQueue
  15.     dispatch_queue_t serialQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"serialQueue"];
  16.     // 阻塞当前的线程,让 serialQueue 执行完成
  17.     dispatch_sync(serialQueue, ^{});
  18.     // 获取数据存储是的线程
  19.     dispatch_queue_t databaseQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"database.queue"];
  20.     // 阻塞当前线程,让 $AppCrashed 事件完成入库
  21.     dispatch_sync(databaseQueue, ^{});
  22.     NSSetUncaughtExceptionHandler(NULL);
  23.    
  24.     int signals[] = {SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV};
  25.     for (int i = 0; i < sizeof(signals) / sizeof(int); i ++) {
  26.         signal(signals[i], SIG_DFL);
  27.     }
  28. }
复制代码
第四步:测试验证
三、采集应用程序异常时的 $AppEnd 事件

​        通过监听应用程序的状态 (UIApplicationDidEnterBackgroundNotification),实现了 $AppEnd 事件的全埋点。但是,一旦应用程序发生异常,我们将采集不到  $AppEnd 事件,这样会造成在用户的行为序列中,出现 $AppStart 事件和  $AppEnd 事件不成对的情况。因此,在应用程序发生崩溃时,我们需要补发  $AppEnd 事件。
第一步:在 - trackAppCrashedWithException: 方法中,补发 $AppEnd 事件
  1. - (void)trackAppCrashedWithException:(NSException *)exception {
  2.     NSMutableDictionary *properties = [NSMutableDictionary dictionary];
  3.     // 异常名称
  4.     NSString *name = [exception name];
  5.     // 出现异常的原因
  6.     NSString *reason = [exception reason];
  7.     // 异常的堆栈信息
  8.     NSArray *stacks = [exception callStackSymbols] ?: [NSThread callStackSymbols];
  9.     // 将异常信息组装
  10.     NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
  11.     properties[@"$app_crashed_reason"] = exceptionInfo;
  12.     [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
  13.    
  14.     // 采集 $AppEnd 回调 block
  15.     dispatch_block_t trackAppEndBlock = ^ {
  16.         // 判断应用是否处于运行状态
  17.         if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive) {
  18.             // 触发事件
  19.             [[SensorsAnalyticsSDK sharedInstance] track:@"$AppEnd" properties:nil];
  20.         }
  21.     };
  22.     // 获取主线程
  23.     dispatch_queue_t mainQueue = dispatch_get_main_queue();
  24.     // 判断当前线程是否为主线程
  25.     if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(mainQueue)) == 0) {
  26.         // 如果当前线程是主线程,直接调用 block
  27.         trackAppEndBlock();
  28.     } else {
  29.         // 如果当前线程不是主线程,同步调用block
  30.         dispatch_sync(mainQueue, trackAppEndBlock);
  31.     }
  32.    
  33.     // 获取 seasorsAnalyticsSDK 中的 serialQueue
  34.     dispatch_queue_t serialQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"serialQueue"];
  35.     // 阻塞当前的线程,让 serialQueue 执行完成
  36.     dispatch_sync(serialQueue, ^{});
  37.     // 获取数据存储是的线程
  38.     dispatch_queue_t databaseQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"database.queue"];
  39.     // 阻塞当前线程,让 $AppCrashed 事件完成入库
  40.     dispatch_sync(databaseQueue, ^{});
  41.     NSSetUncaughtExceptionHandler(NULL);
  42.    
  43.     int signals[] = {SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV};
  44.     for (int i = 0; i < sizeof(signals) / sizeof(int); i ++) {
  45.         signal(signals[i], SIG_DFL);
  46.     }
  47. }
复制代码
第二步:测试验证

来源:https://www.cnblogs.com/r360/p/16369795.html
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4