iOS中捕獲日志與異常示例詳解
前言
在平時自己調(diào)試的時候,可以直接連接電腦,直接在窗口中查看結果。但是在測試人員測試,或者灰度測試的時候,怎么才能拿到日志呢?最先想到的肯定是輸出到本地文件,然后在需要的時候進行上傳。
分享一段之前找到的方法,下面的代碼提供了兩個主要功能:
– 把日志輸出到文件中
– 捕捉異常信息
【解析都寫在注釋中了】
示例代碼
- (void)redirectNSLogToDocumentFolder
{
//如果已經(jīng)連接Xcode調(diào)試則不輸出到文件
//該函數(shù)用于檢測輸出 (STDOUT_FILENO) 是否重定向 是個 Linux 程序方法
if(isatty(STDOUT_FILENO)) {
return;
}
// 判斷 當前是否在 模擬器環(huán)境 下 在模擬器不保存到文件中
UIDevice *device = [UIDevice currentDevice];
if([[device model] hasSuffix:@"Simulator"]){
return;
}
//將NSlog打印信息保存到Document目錄下的Log文件夾下
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [fileManager fileExistsAtPath:logDirectory];
if (!fileExists) {
[fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //每次啟動后都保存一個新的日志文件中
NSString *dateStr = [formatter stringFromDate:[NSDate date]];
NSString *logFilePath = [logDirectory stringByAppendingFormat:@"/%@.log",dateStr];
// 將log輸入到文件
freopen([logFilePath cStringUsingEncoding:NSUTF8StringEncoding], "a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSUTF8StringEncoding], "a+", stderr);
//未捕獲的Objective-C異常日志
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
}
之前看的時候,對 NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler) 這個用法一知半解,去翻了一下源碼,這個方法是在 Foundation 中。
api 中的定義是Changes the top-level error handler ,Sets the top-level error-handling function where you can perform last-minute logging before the program terminates. 通過替換掉最高級別的 handle 方法,可以在程序終止之前可以獲取到崩潰信息,并執(zhí)行相應的操作,比如保存本地,或者上報。
方法調(diào)用為:
void NSSetUncaughtExceptionHandler(NSUncaughtExceptionHandler *);
傳入的是一個 NSUncaughtExceptionHandler 的指針。
typedef void NSUncaughtExceptionHandler(NSException *exception);
意思就是需要一個 返回 void 并且參數(shù)為 NSException *exception 的函數(shù)指針。
你想要,那我就給你!
所以下面有個 C 語言的函數(shù),你看這個寫法和 OC 的聲明也不一樣。
void UncaughtExceptionHandler(NSException* exception)
{
NSString* name = [ exception name ];
NSString* reason = [ exception reason ];
NSArray* symbols = [ exception callStackSymbols ]; // 異常發(fā)生時的調(diào)用棧
NSMutableString* strSymbols = [ [ NSMutableString alloc ] init ]; //將調(diào)用棧拼成輸出日志的字符串
for ( NSString* item in symbols )
{
[ strSymbols appendString: item ];
[ strSymbols appendString: @"\r\n" ];
}
//將crash日志保存到Document目錄下的Log文件夾下
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Log"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:logDirectory]) {
[fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateStr = [formatter stringFromDate:[NSDate date]];
NSString *crashString = [NSString stringWithFormat:@"<- %@ ->[ Uncaught Exception ]\r\nName: %@, Reason: %@\r\n[ Fe Symbols Start ]\r\n%@[ Fe Symbols End ]\r\n\r\n", dateStr, name, reason, strSymbols];
//把錯誤日志寫到文件中
if (![fileManager fileExistsAtPath:logFilePath]) {
[crashString writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}else{
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
[outFile seekToEndOfFile];
[outFile writeData:[crashString dataUsingEncoding:NSUTF8StringEncoding]];
[outFile closeFile];
}
//把錯誤日志發(fā)送到郵箱
// NSString *urlStr = [NSString stringWithFormat:@"mailto://XXXXX@126.com?subject=bug報告&body=感謝您的配合!<br><br><br>錯誤詳情:<br>%@",crashString ];
// NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// [[UIApplication sharedApplication] openURL:url];
}
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對各位iOS開發(fā)者們能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
ios實現(xiàn)自動獲取label高度、寬度及最后一個位置詳解
這篇文章主要給大家介紹了關于ios如何實現(xiàn)自動獲取label高度、寬度及最后一個位置的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-10-10
iOS開發(fā)中Date Picker和UITool Bar控件的使用簡介
這篇文章主要介紹了iOS開發(fā)中Date Picker和UITool Bar控件的使用簡介,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-01-01

