ios 將Log日誌重新導向輸出到檔案中儲存,ioslog

來源:互聯網
上載者:User

ios 將Log日誌重新導向輸出到檔案中儲存,ioslog

      對於真機,日誌沒法儲存,不好分析問題。所以有必要將日誌儲存到應用的Docunment目錄下,並設定成共用檔案,這樣才能取出分析。

       首先是日誌輸出,分為c的printf和標準的NSLog輸出,printf會向標準輸出(sedout)列印,而NSLog則是向標準出錯(stderr),我們需要同時讓他們都將日誌列印到一個檔案中。

       例子:

       freopen("xx.log","a+",stdout);

       freopen("xx.log","a+",stderr);

 

具體做法:

 

       // 將NSlog列印資訊儲存到Document目錄下的檔案中

- (void)redirectNSlogToDocumentFolder

{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentDirectory = [paths objectAtIndex:0];

    NSString *fileName = [NSString stringWithFormat:@"dr.log"];// 注意不是NSData!

    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];

    // 先刪除已經存在的檔案

    NSFileManager *defaultManager = [NSFileManager defaultManager];

    [defaultManager removeItemAtPath:logFilePath error:nil];

    

    // 將log輸入到檔案

    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);

    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);

 

       此函數要在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

中調用,這個函數在AppDelegate.m中實現的。

 

       /*******************************************************************************/

// 當真機串連Mac調試的時候把這些注釋掉,否則log只會輸入到檔案中,而不能從xcode的監視器中看到。

    // 如果是真機就儲存到Document目錄下的drm.log檔案中

    UIDevice *device = [UIDevice currentDevice];

    if (![[device model] isEqualToString:@"iPad Simulator"]) {

        // 開始儲存記錄檔

        [self redirectNSlogToDocumentFolder];

    }

/*******************************************************************************/

 

 最後配置共用資料夾:

        在應用程式的Info.plist檔案中添加UIFileSharingEnabled鍵,並將索引值設定為YES。將您希望共用的檔案放在應用程式的Documents目錄。一旦裝置插入到使用者電腦,iTunes 9.1就會在選中裝置的Apps標籤中顯示一個File Sharing地區。此後,使用者就可以向該目錄添加檔案或者將檔案移動到案頭電腦中。如果應用程式支援檔案分享權限設定,當檔案添加到Documents目錄後,應用程式應該能夠識別並做出適當響應。例如說,應用程式可以將新檔案的內容顯示介面上。請不要向使用者展現目錄的檔案清單並詢問他們希望對檔案執行什麼操作。      

       就是說,一旦裝置串連上電腦,可以通過iTune查看指定應用程式的共用資料夾,將檔案拷貝到你的電腦上看。

 

參考串連:

       1.http://hi.baidu.com/ios_zb_com/item/ea528f4a8b1100d8c1a59217

       2.http://www.cnblogs.com/ThankForYou/archive/2012/09/12/2681739.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.