iOS全埋點解決方案-採集奔潰

任淏發表於2022-06-13

前言

​ 採集應用程式奔潰資訊,主要分為以下兩種場景:

  • ​ 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);
    }
}

第二步:測試驗證

相關文章