iOS進(jìn)階補(bǔ)完計(jì)劃--打點(diǎn)上報(bào)、無(wú)痕埋點(diǎn)

最近研習(xí)了美團(tuán)等大廠的一些埋點(diǎn)方案。
還要感謝大神《xuhaoranLeo》的指點(diǎn)。(既然大神沒(méi)空寫(xiě)博客、但我可以代勞哈)。

本文的宗旨是盡量全面、精簡(jiǎn)、滿足我能想到盡量多的埋點(diǎn)需求。

主要通過(guò)以下這些方面來(lái)談?wù)勚新顸c(diǎn)那些事:

  • 打點(diǎn)/上報(bào)的大概流程
  • 日志記錄類型
  • 日志應(yīng)該帶有的數(shù)據(jù)
  • 打點(diǎn)的具體方式
  • 何時(shí)上報(bào)
  • 具體實(shí)現(xiàn)(iOS)

打點(diǎn)/上報(bào)的大概流程

  • 打點(diǎn):當(dāng)發(fā)生需要收集的行為/狀態(tài)時(shí)、將其記錄在日記中。
  • 上報(bào):選擇合適的時(shí)機(jī)將日志上報(bào)。

日志記錄類型

根據(jù)業(yè)務(wù)需要大致可以具有以下類型

  • 頁(yè)面/產(chǎn)品曝光
  • 用戶點(diǎn)擊
  • 性能打點(diǎn)(數(shù)據(jù)庫(kù)操作效率、APP運(yùn)行卡頓)
  • 網(wǎng)絡(luò)監(jiān)控

日志應(yīng)該帶有的數(shù)據(jù)

  • 一切分析時(shí)用得到的數(shù)據(jù)例子:
    行為(點(diǎn)擊、瀏覽)、用戶(uid)、業(yè)務(wù)信息(gid、gtype)等。

  • 關(guān)鍵業(yè)務(wù)的性能監(jiān)聽(tīng)(其實(shí)性能打點(diǎn)我比較推薦單獨(dú)進(jìn)行、畢竟這是開(kāi)發(fā)關(guān)心的、產(chǎn)品分析并不需要):

  • 網(wǎng)絡(luò)請(qǐng)求失敗率、錯(cuò)誤碼
  • 數(shù)據(jù)層操作耗時(shí)、App卡頓堆棧

打點(diǎn)的具體方式

  • 代碼埋點(diǎn):具體業(yè)務(wù)代碼處、手動(dòng)添加埋點(diǎn)代碼。比如衡量圖片上傳、數(shù)據(jù)解析、OI操作的時(shí)間等
  • 聲明埋點(diǎn): 通過(guò)將事件標(biāo)識(shí)、業(yè)務(wù)字段作為屬性添加在響應(yīng)控件上。簡(jiǎn)化代碼埋點(diǎn)的代碼量。
  • 無(wú)痕埋點(diǎn):獲取全部操作、通過(guò)plist文件、決定需要上報(bào)的指定操作《美團(tuán):Mixpanel》
  • 無(wú)埋點(diǎn):上報(bào)所有操作、由服務(wù)器篩選《GrowingIO》

具體實(shí)現(xiàn):

由于每個(gè)項(xiàng)目的需求不同、具體實(shí)現(xiàn)也不一樣。
這里只大概理順?biāo)悸贰?/p>

周期內(nèi)記錄:

既然是統(tǒng)一上報(bào)、就需要在上報(bào)之前將本次周期中所有的指定操作記錄下來(lái)。

  • 每次操作中。由一個(gè)指定的模型(json)進(jìn)行存儲(chǔ)。
  • 而整個(gè)周期中。我們采用一個(gè)單例、單例中有一個(gè)數(shù)組對(duì)單次模型進(jìn)行存儲(chǔ)。
  /*
  * 數(shù)據(jù)存儲(chǔ)模型
  */
  
  @interface KTBehaviorData : NSObject
  @property (nonatomic, strong) NSString *op_type; // 1點(diǎn)擊事件 2頁(yè)面事件 3IO操作
  @property (nonatomic, strong) NSString *page_code; // 頁(yè)面Id
  @property (nonatomic, strong) NSString *event_code; // 事件Id
  @property (nonatomic, strong) NSDictionary *object_dic; // 內(nèi)容Id
  @property (nonatomic, strong) NSString *op_time; // 點(diǎn)擊事件操作時(shí)間
  @property (nonatomic, strong) NSString *start_time; // 頁(yè)面事件開(kāi)始時(shí)間
  @property (nonatomic, strong) NSString *end_time; // 頁(yè)面事件結(jié)束時(shí)間
  
  @end
  
  
  @interface KTBehaviorUpLoadData : NSObject
  @property (nonatomic, strong) NSString *app_type; //
  @property (nonatomic, strong) NSString *app_version;
  @property (nonatomic, strong) NSString *os_type; // 1蘋(píng)果iOS
  @property (nonatomic, strong) NSString *os_version; // 系統(tǒng)版本
  @property (nonatomic, strong) NSString *device_id; // 設(shè)備id
  @property (nonatomic, strong) NSString *user_id; // 用戶id
  @property (nonatomic, strong) NSString *login_account; // 用戶賬號(hào)
  @property (nonatomic, strong) NSString *screen; // 屏幕分辨率...
  @property (nonatomic, strong) NSMutableArray <KTBehaviorData *>*datas;
      
  @end

存儲(chǔ)&&上報(bào):

在APP結(jié)束時(shí)歸檔存儲(chǔ)、APP啟動(dòng)時(shí)上傳給服務(wù)器、上傳失敗則將歸檔數(shù)據(jù)重新寫(xiě)入單例追加。

  • 寫(xiě)入

    @implementation KTBehaviorDataManager
    + (void)load {
    
        //殺死程序 (但當(dāng)程序位于后臺(tái)唄殺死不執(zhí)行)
        __block id observer1 = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillTerminateNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            NSLog(@"殺死程序---將數(shù)據(jù)寫(xiě)入本地");
            //將數(shù)據(jù)寫(xiě)入本地
            [[KTBehaviorDataManager sharedManager] writeBehaviorData];
            
            [[NSNotificationCenter defaultCenter] removeObserver:observer1];
        }];
    
    
    //程序切換至后臺(tái)
        __block id observer2 = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            NSLog(@"程序切換至后臺(tái)---將數(shù)據(jù)寫(xiě)入本地");
            //將數(shù)據(jù)寫(xiě)入本地
            [[KTBehaviorDataManager sharedManager] writeBehaviorData];
            
            [[NSNotificationCenter defaultCenter] removeObserver:observer2];
        }];
    }
    
  • 上傳

    @implementation KTBehaviorDataUpLoader
    + (void)load {
      //程序啟動(dòng)、上報(bào)記錄
      __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
      
          [KTBehaviorDataUpLoader upLoadData];
          [[NSNotificationCenter defaultCenter] removeObserver:observer];
      }];
    }
    

打點(diǎn):

打點(diǎn)的方式有很多、但本質(zhì)上都一樣。只是打點(diǎn)的代碼書(shū)寫(xiě)位置不同而已。

這里有一點(diǎn)需要注意一下:
在將捕獲的信息寫(xiě)入manager的時(shí)候、記得加上安全保障。因?yàn)檎麄€(gè)app里有很多地方都將會(huì)對(duì)manager進(jìn)行操作、雖然出現(xiàn)資源搶奪的問(wèn)題不大、但是并不代表永遠(yuǎn)不會(huì)。

 #import "KTBehaviorDataManager.h"
  - (void)pushKTBehaviorDataWithModel:(KTBehaviorData *)model {
  
      //線程鎖、保證數(shù)據(jù)完整性
      @synchronized(self) {
        [self.data.datas addObject:model];
      }
  
  }

代碼埋點(diǎn)

看著多、但如果你把代碼封裝一下。就會(huì)發(fā)現(xiàn)少很多了

  - (void)submitBtnClick {
      KTBehaviorData *data = [[KTBehaviorData alloc] init];
      data.op_type = @"2";
      data.page_code = @"push";
      data.event_code = @"submitBtnClick";
      data.object_id = @{@"title":@"xx",@"content":@"xx"};
      data.op_time = [NSDate getCurrentTimeStamp];
      [[KTBehaviorDataManager sharedManager] pushKTBehaviorDataWithModel:data];
  }

當(dāng)然、你可以把打點(diǎn)的方法抽離一下、更精簡(jiǎn)一些而不使用Model。不過(guò)到了方法內(nèi)部之后、都一樣。

  [[KTBehaviorDataManager sharedManager] pushKTBehaviorDataWithPageId:@"xxx" objectId:@"xxx"];

稍微高級(jí)點(diǎn)、一個(gè)記錄圖片上傳速度的埋點(diǎn)。

  - (void)upLoadPic {
  
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          // Do the work in background
          KTBehaviorData * data = [KTBehaviorData new];
          data.op_type = @"3";
          data.page_code = @"ViewController";
          data.event_code = @"upLoadPic";
          data.start_time =[KTBehaviorData getNowTimeTimestamp];
          //圖片上傳
          [NSThread sleepForTimeInterval:5];
          
          data.end_time = [KTBehaviorData getNowTimeTimestamp];
          
          [[KTBehaviorDataManager sharedManager] pushKTBehaviorDataWithModel:data];
          NSLog(@"頁(yè)面IO埋點(diǎn)----%@",[data dicValue]);
      });
      
  }

這樣、就完成了一次提交按鈕被點(diǎn)擊的記錄。包括時(shí)間、控制器、事件、參數(shù)等。
只要你的模型結(jié)構(gòu)足夠健壯、我們完全可以用一個(gè)模型記錄APP內(nèi)的各種事件。

  • 結(jié)合剛才說(shuō)的寫(xiě)入&&上報(bào)。大概這樣的效果


    上報(bào)

聲明埋點(diǎn)

通過(guò)runtime為控件動(dòng)態(tài)添加屬性。
然后在創(chuàng)建控件時(shí)為屬性賦值。

  KTBehaviorData *parameter = [[KTBehaviorData alloc] init];
  parameter.bid = @"bid";
  parameter.lab = @{@"poi_id":@"1"};
  button.kt_clickParams = parameter;

然后在事件發(fā)生時(shí)進(jìn)行記錄。


無(wú)痕埋點(diǎn)

簡(jiǎn)而言之、有兩點(diǎn)。

  • 替換方法:通過(guò)swizzle對(duì)事件進(jìn)行hook。
    這里、我提供兩種方式。
  • 1、通過(guò)類別Hook原生方法:網(wǎng)上最普遍的方式。對(duì)event事件、table代理、頁(yè)面生命周期等方法進(jìn)行Hook、但是無(wú)法直接對(duì)業(yè)務(wù)參數(shù)進(jìn)行捕獲。

解決方案可以通過(guò)對(duì)NSObject擴(kuò)展出一個(gè)打點(diǎn)專用結(jié)構(gòu)體來(lái)獲取、但是本質(zhì)上需要污染了業(yè)務(wù)代碼。

  • 2、hook指定Class中的指定方法:然后在指定方法中通過(guò)獲取class指定屬性值的方式捕獲參數(shù)。這要感謝《xuhaoranLeo》提供的方案。

在下文中我會(huì)對(duì)兩種方式進(jìn)行說(shuō)明并且舉例。

  • 篩選記錄:通過(guò)plist文件。通過(guò)文件名:pageId、方法名:enevtId等方式、自動(dòng)為模型參數(shù)賦值。

替換方法:

  • 通過(guò)類別Hook原生方法

現(xiàn)在還在這個(gè)階段大家對(duì)swizzle應(yīng)用都比較頻繁了、沒(méi)什么必要解釋太多。直接貼代碼吧

  • 舉個(gè)例子
    頁(yè)面進(jìn)出、停留時(shí)間:

    @implementation UIViewController (KTHook)
    
    + (void)load {
        static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
        
              SEL originalSelector1 = @selector(viewWillAppear:);
              SEL swizzledSelector1 = @selector(kt_viewWillAppear:);
              [KTHook swizzlingInClass:[self class] originalSelector:originalSelector1 swizzledSelector:swizzledSelector1];
            
              SEL originalSelector2 = @selector(viewWillDisappear:);
              SEL swizzledSelector2 = @selector(kt_viewWillDisappear:);
              [KTHook swizzlingInClass:[self class] originalSelector:originalSelector2 swizzledSelector:swizzledSelector2];
          });
        }
    #pragma mark - Method Swizzling
    - (void)kt_viewWillAppear:(BOOL)animated
    {
      NSLog(@"進(jìn)入");
    
      [[KTBehaviorDataManager sharedManager]pushKTBehaviorDataWithPageId:NSStringFromClass([self class]) time:[KTBehaviorData getNowTimeTimestamp]];
      [self kt_viewWillAppear:animated];
    }
    
    
    - (void)kt_viewWillDisappear:(BOOL)animated
    {
      NSLog(@"離開(kāi)");
      [[KTBehaviorDataManager sharedManager]pushKTBehaviorDataWithPageId:NSStringFromClass([self class]) time:[KTBehaviorData getNowTimeTimestamp]];
      [self kt_viewWillDisappear:animated];
    }
    
頁(yè)面停留時(shí)間

同理、我們通過(guò)對(duì)UIControl的Event事件、UITableView代理等進(jìn)行hook、進(jìn)行無(wú)痕埋點(diǎn)。
具體方式網(wǎng)上有很多、千篇一律。我就不寫(xiě)了、因?yàn)椴环衔蚁胍@取頁(yè)面參數(shù)的需求、貼出兩個(gè)教學(xué)帖想要這么實(shí)現(xiàn)的可以自取。
《iOS 打點(diǎn)方案設(shè)計(jì)》《iOS動(dòng)態(tài)性(二)可復(fù)用而且高度解耦的用戶統(tǒng)計(jì)埋點(diǎn)實(shí)現(xiàn)》

  • hook指定Class中的指定方法

思路就是上面寫(xiě)的。實(shí)現(xiàn)的代碼也不難、hook過(guò)SDK文件的童鞋應(yīng)該都知道。這里為了方便、我們用了一個(gè)封裝好的工具。 《Aspects》

  @implementation NSObject (KTAspectsHook)

  + (void)load {
      __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
          [self setupBehaviorObj];
          [[NSNotificationCenter defaultCenter] removeObserver:observer];
      }];
  }
  
  #pragma mark - private method
  //hook所有需要打點(diǎn)的對(duì)象方法
  - (void)setupBehaviorObj {
  
      Class clazz = NSClassFromString(@"ViewController");
      //具體事件方法
      SEL selector = NSSelectorFromString(@"upLoadPic");
      
      [clazz aspect_hookSelector:selector withOptions:AspectPositionBefore usingBlock:^(id<AspectInfo> aspectInfo) {
          NSLog(@"ViewController中upLoadPic方法被調(diào)用、參數(shù):aaa==%@",[[aspectInfo instance] valueForKey:@"aaa"]);
  
      } error:NULL];
      }
  
  @end

打印:

2018-01-24 14:43:21.419519+0800 kTBehaviorDemo[4587:363679] ViewController中upLoadPic方法被調(diào)用、參數(shù):aaa==我是參數(shù)aaa

這樣、調(diào)用者、調(diào)用方法、參數(shù)。三大要素就都已經(jīng)可以獲取到了。
但如何進(jìn)行批量埋點(diǎn)?

篩選記錄

用plist、這個(gè)網(wǎng)上也很多帖子。之前提的兩個(gè)帖子也都提及了。

上段代碼可以修改如下:

  + (void)setupBehaviorObj {


      NSDictionary *behaviorPlist = [self getBehaviorEvents];

      for (NSString * className in behaviorPlist) {
          //需要hook的Class
          Class clazz = NSClassFromString(className);

          //對(duì)應(yīng)Class需要hook的方法名
          NSDictionary *events = behaviorPlist[className];

          if (events[kBehaviorEvents]) {
              //事件數(shù)組
              for (NSDictionary *event in events[kBehaviorEvents]) {

                  //具體事件方法
                  SEL selector = NSSelectorFromString(event[kBehaviorEventSelectorName]);

                  [clazz aspect_hookSelector:selector withOptions:AspectPositionBefore usingBlock:^(id<AspectInfo> aspectInfo) {

                      //獲取參數(shù)
                      NSMutableDictionary * parameterDic = [NSMutableDictionary new];
                      if (event[kBehaviorParameter]) {

                          NSDictionary * dic = [NSObject properties_apsWithObj:[aspectInfo instance]];
                          for (NSString * parameterStr in event[kBehaviorParameter]) {
    
                              if ([dic valueForKey:parameterStr]) {
                                [parameterDic setValue:[dic valueForKey:parameterStr] forKey:parameterStr];
                              }
                          }
                      }

                      KTBehaviorData * data = [KTBehaviorData new];
                      data.op_time = [KTBehaviorData getNowTimeTimestamp];
                      data.event_code = event[kBehaviorEventId];
                      data.object_dic = parameterDic;
                      data.page_code = event[kBehaviorPageId];
                      data.op_type = event[kBehaviorType];

                      [[KTBehaviorDataManager sharedManager]pushKTBehaviorDataWithModel:data];


                  } error:NULL];

              }
          }
      }

  }

控制臺(tái)信息:


這樣、只要你的plist足夠健壯。確實(shí)可以做到幾乎完全無(wú)痕的埋點(diǎn)。

結(jié)束語(yǔ):

《demo在此》

年前比較忙、但開(kāi)了帖總要填完。所以可能有些錯(cuò)別字和語(yǔ)法坑。

每個(gè)項(xiàng)目的需求不同、情況也不同。所以這只是個(gè)demo、希望能為大家提供一個(gè)思路、并沒(méi)有封裝成一個(gè)SDK。
  • 不同的情況、可以用不同的打點(diǎn)方案。所謂無(wú)痕、并不一定是最好的、太暴力了。
  • 還有就是當(dāng)項(xiàng)目很龐大的時(shí)候、進(jìn)行hook操作、會(huì)不會(huì)影響性能。如果影響了、有沒(méi)有什么改進(jìn)的方式。
  • 如果你有什么好的想法、或者是項(xiàng)目中有什么更好的方案。還望指教。

補(bǔ)充:

經(jīng)測(cè)。
當(dāng)導(dǎo)入方法為300時(shí)、肉眼無(wú)感。
當(dāng)導(dǎo)入方法為3000時(shí)、約1s。
當(dāng)導(dǎo)入方法為30000時(shí)、約15s。
由于在+load中加載、這段時(shí)間會(huì)算入app啟動(dòng)白屏的時(shí)間內(nèi)。


最后

本文主要是自己的學(xué)習(xí)與總結(jié)。如果文內(nèi)存在紕漏、萬(wàn)望留言斧正。如果不吝賜教小弟更加感謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容