程序中引入crash日志文件

来源:互联网 发布:网络咨询护士压力大吗 编辑:程序博客网 时间:2024/05/05 05:53

看安卓crash后都有什么crash日志文件,直接就锁定在哪crash,为什么crash,感觉不错,自己也摸索一下,在iOS程序中我也写了一个crash日志文件,便于更好的监测和修复项目。我在程序入口的时候写入下边的代码:

//异常处理函数
static NSString* CRASHLOG_PATH = @"__pbmobilecrash.log";
void UncaughtExceptionHandler(NSException *exception) {
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    NSString *reason = [exception reason];//非常重要,就是崩溃的原因
    NSString *name = [exception name];//异常类型
    
    NSString *crashLogInfo = [NSString stringWithFormat:@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr];
    DebugLog(@"APP Crash,%@",crashLogInfo);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableFilePath = [documentsDirectory stringByAppendingPathComponent:CRASHLOG_PATH];
    
    char szFilePath[512] = {0};
    [writableFilePath getCString:szFilePath maxLength:sizeof(szFilePath) encoding:NSASCIIStringEncoding];
    
    FILE* hFile = NULL;
    if((hFile = fopen(szFilePath, "a+"))!=NULL)
    {
        NSDate *now = [NSDate date];
        NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString * strDate=[dateformatter stringFromDate:now];
        fprintf(hFile, "\n");
        fprintf(hFile, "%s : \n",[strDate UTF8String]);
        fprintf(hFile, "%s",[crashLogInfo UTF8String]);
        fclose(hFile);
    }
}

然后在程序入口处调用这个方法即可

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);


0 0
原创粉丝点击