1.Pods中导入Sentry类,使用终端pod install安装Sentry到项目中
2.项目中创建Crash类,用于捕获异常,将崩溃前的错误日志保存本地
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Crash : NSObject
// 崩溃时的回调函数
void uncaughtExceptionHandler(NSException *exception);
@end
NS_ASSUME_NONNULL_END
#import "Crash.h"
@implementation Crash
void uncaughtExceptionHandler(NSException *exception){
NSArray *stackArry= [exception callStackSymbols];
NSString *reason = [exception reason];
NSString *name = [exception name];
NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name:%@\nException reatoin:%@\nException stack :%@",name,reason,stackArry];
//NSLog(@"%@",exceptionInfo);
//保存到本地沙盒中
[exceptionInfo writeToFile:[NSString stringWithFormat:@"%@/Documents/Exception.txt",NSHomeDirectory()] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
@end
3.在appdelegate.m中导入Sentry、Crash类
//导入sentry错误异常捕捉
#import "Sentry.h"
//系统捕获异常
#import "Crash.h"
4.在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中进行设置
//启动sentry异常捕获
[self startSentry];
//注册消息处理函数的处理方法
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
//获取本地崩溃日志
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [path stringByAppendingPathComponent:@"Exception.txt"];
NSData *data = [NSData dataWithContentsOfFile:dataPath];
if (data != nil) {
//发送崩溃日志
[self sendExceptionLogWithData:data path:dataPath];
//清除本地崩溃日志
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:dataPath error:nil];
}
#pragma mark - 异常处理
//启动sentry日志捕获
- (void)startSentry {
//1.设置dsn
NSError *error = nil;
SentryClient *client = [[SentryClient alloc] initWithDsn:@"http://56b9d6fd9f4c4ca38ea96f0cc1ebfae6@1.193.162.246:14903/4" didFailWithError:&error];
SentryClient.sharedClient = client;
[SentryClient.sharedClient startCrashHandlerWithError:&error];
if (nil != error) {
NSLog(@"%@", error);
}
//2.开启面包屑高级功能
//SentryClient.sharedClient.maxBreadcrumbs = 100;
[SentryClient.sharedClient enableAutomaticBreadcrumbTracking];
}
- (void)sendExceptionLogWithData:(NSData *)data path:(NSString *)path {
SentryEvent *event = [[SentryEvent alloc] initWithLevel:kSentrySeverityFatal];
event.message = [data mj_JSONString];
//用于判断环境
if ([kServerUrl isEqualToString:@"http://172.16.0.145:50120/gangquan360-app"]) {
event.environment = @"debug";//dev sit uat pro 四个环境
}else if ([kServerUrl isEqualToString:@"http://yfb.gangquan360.com:14701/appapi/gangquan360-app"]){
event.environment = @"preview";//dev sit uat pro 四个环境
}else if ([kServerUrl isEqualToString:@"http://app.gangquan360.com/gangquan360-app"]){
event.environment = @"release";//dev sit uat pro 四个环境
}
//event.extra = dic; //请求参数
[SentryClient.sharedClient sendEvent:event withCompletionHandler:^(NSError * _Nullable error) {
if (nil != error) {
NSLog(@"%@", error);
}
}];
}
项目崩溃后,退出app,再次进入app时,查找本地报错文件是否有数据,如果有数据,将数据传到Sentry后端地址,并清理本地报错日志。