iOS–日志重定向
一、使用场景:
- 有时候我没在调试的时候不方便拿到一些信息。如在真机环境下,我们想测试离线推送,而此时我们的APP并没有在调试环境下,所以拿不到相应的log(日志),这时候就可以使用日志重定向。
二、使用步骤
- 1、appdelegate里面的启动-调用下面方法
-(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/** 重定向log日志 */
if (![[[UIDevice currentDevice] model] isEqualToString:@"iPhone Simulator"]) {
[self redirectNSlogToDocumentFolder];
}
}
-(void)redirectNSlogToDocumentFolder {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"MMddHHmmss"];
NSString *formattedDate = [dateformatter stringFromDate:currentDate];
NSString *fileName = [NSString stringWithFormat:@"rc%@.log", formattedDate];
NSString *logFilePath =
[documentDirectory stringByAppendingPathComponent:fileName];
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+",
stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+",
stderr);
}
- 3、查看log日志–在 Supporting Files 中的 info.plist 中打开 Application supports iTunes file sharin

- 5、滚动到最下面,点击“存储到…”按钮将 Log 存储到桌面,双击打开就能看到 Log 信息了。