iOS全埋点解决方案-采集崩溃

前言

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

  • ​ NSException 异常
  • ​ Unix 信号异常

一、NSException 异常

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

1.1 捕获 NSException

​ 我们可以通过 NSSetUNcaughtExceptionHandle 函数来全局设置异常处理函数,然后手机异常堆栈信息并触发响应的事件($AppCrashed),来实现 NSException 异常的全埋点。

第一步:在 SensorsSDK 项目中创建 SensorsAnalyticsExtensionHandler 类,并增加 + sharedInstance 方法并实现

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface SensorsAnalyticsExtensionHandler : NSObject

+ (instancetype)sharedInstance;

@end

NS_ASSUME_NONNULL_END
@implementation SensorsAnalyticsExtensionHandler

+ (instancetype)sharedInstance {
    static SensorsAnalyticsExtensionHandler *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SensorsAnalyticsExtensionHandler alloc] init];
    });
    return instance;
}
@end

第二步:实现 -init ,并通过 NSSetUncaughtExceptionHandler 函数全局设置异常处理函数,然后再全局处理函数中采集异常信息,并触发 $AppCrashed 事件。其中,异常的堆栈信息会放到 $app_crashed_reason 事件属性中。

//
//  SensorsAnalyticsExtensionHandler.m
//  SensorsSDK
//
//  Created by renhao on 2022/4/22.
//

#import "SensorsAnalyticsExtensionHandler.h"

#import "SensorsAnalyticsSDK.h"

@implementation SensorsAnalyticsExtensionHandler

+ (instancetype)sharedInstance {
    static SensorsAnalyticsExtensionHandler *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SensorsAnalyticsExtensionHandler alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSSetUncaughtExceptionHandler(&sensorsdata_uncaught_excepting_handler);
    }
    return self;
}

static void sensorsdata_uncaught_excepting_handler(NSException *exception) {
    // 采集 $AppCrashec 事件
    [[SensorsAnalyticsExtensionHandler sharedInstance] trackAppCrashedWithException:exception];
}

- (void)trackAppCrashedWithException:(NSException *)exception {
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    // 异常名称
    NSString *name = [exception name];
    // 出现异常的原因
    NSString *reason = [exception reason];
    // 异常的堆栈信息
    NSArray *stacks = [exception callStackSymbols];
    // 将异常信息组装
    NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
    properties[@"$app_crashed_reason"] = exceptionInfo;
    [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
    
    NSSetUncaughtExceptionHandler(NULL);
}

@end

第三步:在 SensorsAnalyticsSDK 的 - initWithServerURL: 方法中初始化 SensorsAnalyticsExtensionHandler 的单例对象

#import "SensorsAnalyticsExtensionHandler.h"

- (instancetype)initWithServerURL:(NSString *)urlString {
    self = [super init];
    if (self) {
        _automaticProperties = [self collectAutomaticProperties];

        // 设置是否需是被动启动标记
        _launchedPassively = UIApplication.sharedApplication.backgroundTimeRemaining != UIApplicationBackgroundFetchIntervalNever;
        
        _loginId = [[NSUserDefaults standardUserDefaults] objectForKey:SensorsAnalyticsLoginId];
        
        _trackTimer = [NSMutableDictionary dictionary];
        
        _enterBackgroundTrackTimerEvents = [NSMutableArray array];
        
        _fileStroe = [[SensorsAnalyticsFileStore alloc] init];
        
        _database = [[SensorsAnalyticsDatabase alloc] init];
        
        _network = [[SensorsAnalyticsNetwork alloc] initWithServerURL:[NSURL URLWithString:urlString]];
        
        NSString *queueLabel = [NSString stringWithFormat:@"cn.sensorsdata.%@.%p", self.class, self];
        _serialQueue = dispatch_queue_create(queueLabel.UTF8String, DISPATCH_QUEUE_SERIAL);
        
        _flushBulkSize = 100;
        
        _flushInterval = 15;
        
        [SensorsAnalyticsExtensionHandler sharedInstance];
        
        // 添加应用程序状态监听
        [self setupListeners];
        
        [self startFlushTimer];
    }
    return self;
}

第四步:测试验证

        NSArray *array = @[@"first"];
        NSLog(@"%@", array[1]);
{
  "propeerties" : {
    "$model" : "arm64",
    "$manufacturer" : "Apple",
    "$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
    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)",
    "$lib_version" : "1.0.0",
    "$os" : "iOS",
    "$app_version" : "1.0",
    "$os_version" : "15.4",
    "$lib" : "iOS"
  },
  "event" : "$AppCrashed",
  "time" : 1650616086146,
  "distinct_id" : "3E0DD30F-4F2F-425C-8323-FA43C149CE27"
}

1.2 传递 UncaughtExceptionHandler

​ 问题描述:在应用程序实际开发过程中,可能会采集多个 SDK,如果这些 SDK 都按照上面介绍的方法采集异常信息,总会有一些 SDK 采集不到异常信息。这是因为通过 NSSetUncaughtExceptionHandler 函数设置的是一个全局异常处理函数,后面设置的异常处理函数会自动覆盖前面设置的异常处理函数。

​ 解决方法:在调用 NSSetUncaughtExceptionHandler 函数设置全局异常处理函数前,先通过 NSGetUncaughtExceptionHandler 函数获取之前已设置的异常处理函数并保存,在处理完异常信息采集后,再主动调用已备份的处理函数(让所有的异常处理函数形成链条),即可解决上面提到的覆盖问题。

#import "SensorsAnalyticsExtensionHandler.h"

#import "SensorsAnalyticsSDK.h"

@interface SensorsAnalyticsExtensionHandler()

/// 保存之前已设置的异常处理函数
@property (nonatomic) NSUncaughtExceptionHandler *previousExceptionHandler;

@end

@implementation SensorsAnalyticsExtensionHandler

+ (instancetype)sharedInstance {
    static SensorsAnalyticsExtensionHandler *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SensorsAnalyticsExtensionHandler alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _previousExceptionHandler = NSGetUncaughtExceptionHandler();
        NSSetUncaughtExceptionHandler(&sensorsdata_uncaught_excepting_handler);
    }
    return self;
}

static void sensorsdata_uncaught_excepting_handler(NSException *exception) {
    // 采集 $AppCrashec 事件
    [[SensorsAnalyticsExtensionHandler sharedInstance] trackAppCrashedWithException:exception];

    NSUncaughtExceptionHandler *handle = [SensorsAnalyticsExtensionHandler sharedInstance].previousExceptionHandler;
    if (handle) {
        handle(exception);
    }
}

- (void)trackAppCrashedWithException:(NSException *)exception {
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    // 异常名称
    NSString *name = [exception name];
    // 出现异常的原因
    NSString *reason = [exception reason];
    // 异常的堆栈信息
    NSArray *stacks = [exception callStackSymbols];
    // 将异常信息组装
    NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
    properties[@"$app_crashed_reason"] = exceptionInfo;
    [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
    
    NSSetUncaughtExceptionHandler(NULL);
}

@end

二、捕获信号

2.1 Mach 异常和 Unix 信号

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

2.2 捕获 Unix 信号异常

第一步:新增捕获 Unix 信号的处理函数

static NSString * const SensorsDataSignalExceptionHandlerName = @"SignalExceptionHandler";

static NSString * const SensorsDataSignalExceptionHandlerUserInfo = @"SignalExceptionHandlerUserIfo";

static void sensorsdata_signal_exception_handler(int sig, struct __siginfo *info, void *context) {
    NSDictionary *userInfo = @{SensorsDataSignalExceptionHandlerUserInfo: @(sig)};
    NSString *reason = [NSString stringWithFormat:@"Signal %d was raised.", sig];
    // 创建一个异常对象, 用于采集异常信息
    NSException *exception = [NSException exceptionWithName:SensorsDataSignalExceptionHandlerName reason:reason userInfo:userInfo];
    
    SensorsAnalyticsExtensionHandler *handler = [SensorsAnalyticsExtensionHandler sharedInstance];
    [handler trackAppCrashedWithException:exception];
}

第二步:在 - init 初始化方法中,注册信号处理函数

- (instancetype)init {
    self = [super init];
    if (self) {
        _previousExceptionHandler = NSGetUncaughtExceptionHandler();
        NSSetUncaughtExceptionHandler(&sensorsdata_uncaught_excepting_handler);
        
        // 定义信号集结构体
        struct sigaction sig;
        // 将信号集初始化为空
        sigemptyset(&sig.sa_mask);
        // 在处理函数中传入__siginfo参数
        sig.sa_flags = SA_SIGINFO;
        // 设置信号集处理函数
        sig.sa_sigaction = &sensorsdata_signal_exception_handler;
        // 定义需要采集的信号类型
        int signals[] = {SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV};
        for(int i = 0; i < sizeof(signals) / sizeof(int); i++){
            // 注册信号处理
            int err = sigaction(signals[i], &sig, NULL);
            if (err) {
                NSLog(@"Errored while trying to set up sigaction for signal %d", signals[i]);
            }
        }
    }
    return self;
}

第三步:修改 - trackAppCrashedWithException: 方法,当异常对象中没有堆栈信息时,就是默认获取当前线程的堆栈信息(由于 Unix 信息异常对象是我们自己构建的,因此并没有堆栈信息)

- (void)trackAppCrashedWithException:(NSException *)exception {
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    // 异常名称
    NSString *name = [exception name];
    // 出现异常的原因
    NSString *reason = [exception reason];
    // 异常的堆栈信息
    NSArray *stacks = [exception callStackSymbols] ?: [NSThread callStackSymbols];
    // 将异常信息组装
    NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
    properties[@"$app_crashed_reason"] = exceptionInfo;
    [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
    
    // 获取 seasorsAnalyticsSDK 中的 serialQueue
    dispatch_queue_t serialQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"serialQueue"];
    // 阻塞当前的线程,让 serialQueue 执行完成
    dispatch_sync(serialQueue, ^{});
    // 获取数据存储是的线程
    dispatch_queue_t databaseQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"database.queue"];
    // 阻塞当前线程,让 $AppCrashed 事件完成入库
    dispatch_sync(databaseQueue, ^{});
    NSSetUncaughtExceptionHandler(NULL);
    
    int signals[] = {SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV};
    for (int i = 0; i < sizeof(signals) / sizeof(int); i ++) {
        signal(signals[i], SIG_DFL);
    }
}

第四步:测试验证

三、采集应用程序异常时的 $AppEnd 事件

​ 通过监听应用程序的状态 (UIApplicationDidEnterBackgroundNotification),实现了 $AppEnd 事件的全埋点。但是,一旦应用程序发生异常,我们将采集不到 $AppEnd 事件,这样会造成在用户的行为序列中,出现 $AppStart 事件和 $AppEnd 事件不成对的情况。因此,在应用程序发生崩溃时,我们需要补发 $AppEnd 事件。

第一步:在 - trackAppCrashedWithException: 方法中,补发 $AppEnd 事件

- (void)trackAppCrashedWithException:(NSException *)exception {
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    // 异常名称
    NSString *name = [exception name];
    // 出现异常的原因
    NSString *reason = [exception reason];
    // 异常的堆栈信息
    NSArray *stacks = [exception callStackSymbols] ?: [NSThread callStackSymbols];
    // 将异常信息组装
    NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name: %@\n Exception reason: %@\n Exception stack: %@", name, reason, stacks];
    properties[@"$app_crashed_reason"] = exceptionInfo;
    [[SensorsAnalyticsSDK sharedInstance] track:@"$AppCrashed" properties:properties];
    
    // 采集 $AppEnd 回调 block
    dispatch_block_t trackAppEndBlock = ^ {
        // 判断应用是否处于运行状态
        if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive) {
            // 触发事件
            [[SensorsAnalyticsSDK sharedInstance] track:@"$AppEnd" properties:nil];
        }
    };
    // 获取主线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    // 判断当前线程是否为主线程
    if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(mainQueue)) == 0) {
        // 如果当前线程是主线程,直接调用 block
        trackAppEndBlock();
    } else {
        // 如果当前线程不是主线程,同步调用block
        dispatch_sync(mainQueue, trackAppEndBlock);
    }
    
    // 获取 seasorsAnalyticsSDK 中的 serialQueue
    dispatch_queue_t serialQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"serialQueue"];
    // 阻塞当前的线程,让 serialQueue 执行完成
    dispatch_sync(serialQueue, ^{});
    // 获取数据存储是的线程
    dispatch_queue_t databaseQueue = [[SensorsAnalyticsSDK sharedInstance] valueForKey:@"database.queue"];
    // 阻塞当前线程,让 $AppCrashed 事件完成入库
    dispatch_sync(databaseQueue, ^{});
    NSSetUncaughtExceptionHandler(NULL);
    
    int signals[] = {SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV};
    for (int i = 0; i < sizeof(signals) / sizeof(int); i ++) {
        signal(signals[i], SIG_DFL);
    }
}

第二步:测试验证

posted @ 2022-06-13 10:01  任淏  阅读(881)  评论(1编辑  收藏  举报