【代碼筆記】將log日誌儲存到檔案,代碼筆記log日誌

來源:互聯網
上載者:User

【代碼筆記】將log日誌儲存到檔案,代碼筆記log日誌

代碼:

#import "AppDelegate.h"#import "RootViewController.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.        RootViewController *rootVC=[[RootViewController alloc]init];    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:rootVC];    self.window.rootViewController=nav;            //將log日誌儲存到檔案    #ifdef  BH_DEBUG         [self redirectNSLogToDocumentFolder];    #else            #endif        self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];    return YES;}- (void)redirectNSLogToDocumentFolder{    //如果已經串連Xcode調試則不輸出到檔案    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:NSASCIIStringEncoding], "a+", stdout);    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);        //未捕獲的Objective-C異常日誌    NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);}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://test@163.com?subject=bug報告&body=感謝您的配合!<br><br><br>錯誤詳情:<br>%@",crashString ];    //    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];    //    [[UIApplication sharedApplication] openURL:url];}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.