采集应用程序崩溃信息,主要分为以下两种场景:
NSException 异常是 Objective-C 代码抛出的异常。在 iOS 应用程序中,最常见就是通过 @throw 抛出的异常。比如,常见的数组越界访问异常。
我们可以通过 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"
}
问题描述:在应用程序实际开发过程中,可能会采集多个 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
Mach 是 Mac OS 和 iOS 操作系统的微内核,Mach 异常就是最底层的内核级异常。在 iOS 系统中,每个 Thread、Task、Host 都有一个异常端口数据。开发者可以通过设置 Thread、Task、Host 的异常端口来捕获 Mach 异常。Mach 异常会被转换成相应的 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);
}
}
第四步:测试验证
通过监听应用程序的状态 (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);
}
}
第二步:测试验证
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',
当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
相信很多人在录制视频的时候都会遇到各种各样的问题,比如录制的视频没有声音。屏幕录制为什么没声音?今天小编就和大家分享一下如何录制音画同步视频的具体操作方法。如果你有录制的视频没有声音,你可以试试这个方法。 一、检查是否打开电脑系统声音相信很多小伙伴在录制视频后会发现录制的视频没有声音,屏幕录制为什么没声音?如果当时没有打开音频录制,则录制好的视频是没有声音的。因此,建议在录制前进行检查。屏幕上没有声音,很可能是因为你的电脑系统的声音被禁止了。您只需打开电脑系统的声音,即可录制音频和图画同步视频。操作方法:步骤1:点击电脑屏幕右下侧的“小喇叭”图案,在上方的选项中,选择“声音”。 步骤2:在“声
首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有, 也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
深度学习部署:Windows安装pycocotools报错解决方法1.pycocotools库的简介2.pycocotools安装的坑3.解决办法更多Ai资讯:公主号AiCharm本系列是作者在跑一些深度学习实例时,遇到的各种各样的问题及解决办法,希望能够帮助到大家。ERROR:Commanderroredoutwithexitstatus1:'D:\Anaconda3\python.exe'-u-c'importsys,setuptools,tokenize;sys.argv[0]='"'"'C:\\Users\\46653\\AppData\\Local\\Temp\\pip-instal
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上