iOS日志及崩溃抓取

在日常开发及测试中很容易出现比较难以复现的崩溃,这种bug往往让我们无处下手,日志抓取帮我们很好的解决了这个问题。

DDLog的使用

首先可以在pch文件中定义log等级

static const DDLogLevel ddLogLevel = DDLogLevelVerbose;

在application:didFinishLaunchingWithOptions方法中调用如下代码即可发起日志记录功能

   // DDTTYLogger,你的日志语句将被发送到Xcode控制台
    [DDLog addLogger:[DDTTYLogger sharedInstance] withLevel:DDLogLevelWarning];
    // DDASLLogger,你的日志语句将被发送到苹果文件系统、你的日志状态会被发送到 Console.app
    [DDLog addLogger:[DDASLLogger sharedInstance] withLevel:DDLogLevelAll];
    
    // DDFileLogger,你的日志语句将写入到一个文件中,默认路径在沙盒的Library/Caches/Logs/目录下,文件名为bundleid+空格+日期.log。
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    fileLogger.rollingFrequency = 60 * 60 * 24; // 刷新频率为24小时
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7; // 保存一周的日志,即7天
    [DDLog addLogger:fileLogger];

崩溃日志抓取

在崩溃出现时,可通过NSSetUncaughtExceptionHandler里指定崩溃出现后调用的方法,首先定义CatchCrash对象并对外部声明其崩溃时的方法:

//在AppDelegate中注册后,程序崩溃时会执行的方法
void uncaughtExceptionHandler(NSException *exception)
{
    //获取系统当前时间,(注:用[NSDate date]直接获取的是格林尼治时间,有时差)
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *crashTime = [formatter stringFromDate:[NSDate date]];
    //异常的堆栈信息
    NSArray *stackArray = [exception callStackSymbols];
    //出现异常的原因
    NSString *reason = [exception reason];
    //异常名称
    NSString *name = [exception name];
    
    //设备信息....
    
    //拼接错误信息
    NSString *exceptionInfo = [NSString stringWithFormat:@"crashTime: %@ Exception reason: %@
Exception name: %@
Exception stack:%@", crashTime, name, reason, stackArray];
    
    //通过DLog把报错信息写入到log日志中
    DDLogError(@"%@", exceptionInfo);
}

然后在ViewController制造log以及崩溃信息

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *crashTime = [formatter stringFromDate:[NSDate date]];
    DDLogWarn(@"记录打印信息------%@", crashTime);
}

- (IBAction)crashButton:(id)sender {
    NSArray * arr = @[@"1", @"2"];
    NSLog(@"%@", arr[2]);
//    [NSException raise:@"Crash Action" format:@""];
}

日志默认记录地址为Library/Caches/Logs,查看日志如下:

项目地址:https://gitee.com/langtaosha/DDLogDemo

考虑到网络请求对电量及流量的影响,日志的上传一般都不是即时的,可选择在wifi环境下上传经过ZipArchive处理过的压缩包,争取对用户的影响降到最小

原文地址:https://www.cnblogs.com/GoodmorningMr/p/11452285.html