在平常的工做中,日誌是不可缺乏的一個環節,平時本身調試的時候,能夠直接鏈接電腦,直接在窗口中查看結果。javascript
可是在測試人員測試,或者灰度測試的時候,怎麼才能拿到日誌呢?最早想到的確定是輸出到本地文件,而後在須要的時候進行上傳。java
分享一段以前找到的方法,下面的代碼提供了兩個主要功能:api
【解析都寫在註釋中了】app
- (void)redirectNSLogToDocumentFolder
{
//若是已經鏈接Xcode調試則不輸出到文件
//該函數用於檢測輸出 (STDOUT_FILENO) 是否重定向 是個 Linux 程序方法
if(isatty(STDOUT_FILENO)) {
return;
}
// 判斷 當前是否在 模擬器環境 下 在模擬器不保存到文件中
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 方法,能夠在程序終止以前能夠獲取到崩潰信息,並執行相應的操做,好比保存本地,或者上報。測試
方法調用爲:
void NSSetUncaughtExceptionHandler(NSUncaughtExceptionHandler *);atom
傳入的是一個 NSUncaughtExceptionHandler 的指針。url
typedef void NSUncaughtExceptionHandler(NSException *exception);spa
意思就是須要一個 返回 void 而且參數爲 NSException *exception 的函數指針。指針
你想要,那我就給你!
因此下面有個 C 語言的函數,你看這個寫法和 OC 的聲明也不同。
void UncaughtExceptionHandler(NSException* exception)
{
NSString* name = [ exception name ];
NSString* reason = [ exception reason ];
NSArray* symbols = [ exception callStackSymbols ]; // 異常發生時的調用棧
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];
}
//把錯誤日誌發送到郵箱
// 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];
}複製代碼