前言
在平時自己調試的時候,可以直接連接電腦,直接在窗口中查看結果。但是在測試人員測試,或者灰度測試的時候,怎么才能拿到日志呢?最先想到的肯定是輸出到本地文件,然后在需要的時候進行上傳。
分享一段之前找到的方法,下面的代碼提供了兩個主要功能:
– 把日志輸出到文件中
– 捕捉異常信息
【解析都寫在注釋中了】
示例代碼
- (void)redirectNSLogToDocumentFolder{//如果已經連接Xcode調試則不輸出到文件//該函數用于檢測輸出 (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í)行相應的操作,比如保存本地,或者上報。
方法調用為:
void NSSetUncaughtExceptionHandler(NSUncaughtExceptionHandler *);
傳入的是一個 NSUncaughtExceptionHandler 的指針。
typedef void NSUncaughtExceptionHandler(NSException *exception);
意思就是需要一個 返回 void 并且參數為 NSException *exception 的函數指針。
你想要,那我就給你!
所以下面有個 C 語言的函數,你看這個寫法和 OC 的聲明也不一樣。
void UncaughtExceptionHandler(NSException* exception){NSString* name = [ exception name ];NSString* reason = [ exception reason ];NSArray* symbols = [ exception callStackSymbols ]; // 異常發(fā)生時的調用棧NSMutableString* strSymbols = [ [ NSMutableString alloc ] init ]; //將調用棧拼成輸出日志的字符串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];}總結
以上就是這篇文章的全部內容了,希望本文的內容對各位iOS開發(fā)者們能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答