您的位置:首页 > 移动开发 > IOS开发

一种ios模拟器实时查看日志方法

2014-10-23 21:57 435 查看
下载本文pdf

我们在用xcode调试ios程序时通常会用NSLog来输出日志,默认是输出到xcode的debug控制台的,虽然我们可以通过字符串查找来看日志,但假如我们想通过过滤方式只查看特定的日志时,尤其时在实时输出的同时查看就很不方便了,在android的开发中可以通过TAG来输出,在windows我们可以通过wintail,在linux有tail下来查看,在mac当然也有tail和grep命令,那么我们是否可以利用这些工具呢?当然是可以的。将日志输出到文件,然后用tail, grep等命令对日志文件进行过滤查看

一,重定向输出日志

- (void) redirectConsoleLogToDocumentFolder
{
#ifdef DEBUG //只在调试时使用,不然在真机下也会输出到沙盒目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//首先输出日志文件的路径,方便我们定位目录
NSLog(@"log path:%@", documentsDirectory);

//先删除上次输出的日志
NSString *logFile = [[NSString alloc] initWithFormat:@"%@/log.txt", documentsDirectory];
NSError *err;
[[NSFileManager defaultManager] removeItemAtPath:logFile error:&err];

//重定向NSLog输出
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"log.txt"];
freopen([logPath fileSystemRepresentation], "a+", stderr);
#endif
}


我们在AppDelegate添加调用这个方法

- (BOOL)application:(UIApplication *) applicationdidFinishLaunchingWithOptions:(NSDictionary *) launchOptions {
[self redirectConsoleLog];
return YES;
}


二,开始调试程序

我们先在xcode的output窗口看到我们日志的输出路径(这个路径只要模拟器不重启就不会改变):



三, 查看日志

打开命令行终端,我们先定位到这个目录:



通过tail命令实时查看日志

#tail -f console.log

也可以添加过滤条件

#tail -f console.log | grep -s "lbs"



你也可以开多个窗口通过不同的过滤条件来查看日志;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: