---
title: "(转)[IOS]将Log日志重定向输出到文件中保存"
author: "繁星水"
date: "2019-09-30T17:33:37Z"
tags: ["log"]
categories: ["移动开发"]
slug: "ios-log"
draft: false
lastmod: "2019-09-30T17:33:37Z"
id: 2508535
url: "https://jameskaron.iteye.com/blog/2508535"
---

转自:https://www.cnblogs.com/Camier-myNiuer/p/4267426.html

 

 对于真机，日志没法保存，不好分析问题。所以有必要将日志保存到应用的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查看指定应用程序的共享文件夹，将文件拷贝到你的电脑上看。