使用 NSSetUncaughtExceptionHandler 方法,将异常信息写入日志文件。
首先新加一个类 DSQCrashCatch ,.h中定义方法:
+ (void)catchCrash;
在 didFinishLaunchingWithOptions 中设置该方法:
[DSQCrashCatch catchCrash]
@implementation DSQCrashCatch
void uncaughtExceptionHandler(NSException * exception);
+ (void)catchCrash {
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
});
}
void uncaughtExceptionHandler(NSException * exception){
//获取系统当前时间,(注:用[NSDate date]直接获取的是格林尼治时间,有时差)
NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
[formattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString*crashTime = [formatterstringFromDate:[NSDatedate]];
[formattersetDateFormat:@"HH-mm-ss"];
NSString*crashTimeStr = [formatterstringFromDate:[NSDatedate]];
[formattersetDateFormat:@"yyyyMMdd"];
NSString*crashDate = [formatterstringFromDate:[NSDatedate]];
//异常的堆栈信息
NSArray*stackArray = [exceptioncallStackSymbols];
//出现异常的原因
NSString*reason = [exceptionreason];
//异常名称
NSString*name = [exceptionname];
//拼接错误信息
NSString *exceptionInfo = [NSString stringWithFormat:@"CrashTime: %@\nException reason: %@\nException name: %@\nException call stack:%@\n", crashTime, name, reason, stackArray];
//把错误信息保存到本地文件,设置errorLogPath路径下
//并且经试验,此方法写入本地文件有效。
// NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString*errorLogPath = [NSStringstringWithFormat:@"%@/CrashLogs/%@/",NSHomeDirectory(), crashDate];
NSFileManager *manager = [NSFileManager defaultManager];
if(![managerfileExistsAtPath:errorLogPath]) {
[managercreateDirectoryAtPath:errorLogPath withIntermediateDirectories:true attributes:nil error:nil];
}
errorLogPath = [errorLogPathstringByAppendingFormat:@"%@.log",crashTimeStr];
NSError*error =nil;
NSLog(@"%@", errorLogPath);
BOOLisSuccess = [exceptionInfowriteToFile:errorLogPathatomically:YESencoding:NSUTF8StringEncodingerror:&error];
if(!isSuccess) {
NSLog(@"将crash信息保存到本地失败: %@", error.userInfo);
}
}
@end
网友评论