iOS日志及崩溃抓取

本文介绍了在iOS开发中如何使用DDLog进行日志记录,并通过NSSetUncaughtExceptionHandler捕获崩溃日志。详细说明了如何设置日志等级、记录崩溃信息,以及日志的默认存储位置。提供了一个DDLogDemo项目的链接,帮助开发者理解实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在日常开发及测试中很容易出现比较难以复现的崩溃,这种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: %@\nException name: %@\nException 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处理过的压缩包,争取对用户的影响降到最小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值