`
isiqi
  • 浏览: 16080796 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

iPhone开发技巧之调试篇(2)— 保存日志

阅读更多

大部分人调试程序都是看日志吧,这里我就给大家总结一下iphone程序中添加保存日志的方法。

Objective-C开发程序的时候,有专门的日志操作类NSLog,它将指定的输出到标准的错误输出上(stderr)。我们可以利用它在Xcode的日志输出窗口,或者是输出到具体的文件当中。

下面是我在程序中常用到的日志宏,用DEBUG开关管理,也就是说只有在DEBUG模式下才让日志输出 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifdef DEBUG
#  define LOG(fmt, ...) do {                                            \
        NSString* file = [[NSString alloc] initWithFormat:@"%s", __FILE__]; \
        NSLog((@"%@(%d) " fmt), [file lastPathComponent], __LINE__, ##__VA_ARGS__); \
        [file release];                                                 \
    } while(0)
#  define LOG_METHOD NSLog(@"%s", __func__)
#  define LOG_CMETHOD NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd))
#  define COUNT(p) NSLog(@"%s(%d): count = %d\n", __func__, __LINE__, [p retainCount]);
#  define LOG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0)
#else
#  define LOG(...)
#  define LOG_METHOD
#  define LOG_CMETHOD
#  define COUNT(p)
#  define LOG_TRACE(x)
#endif

可以看到,除了标准的用户定义输出外,我还加入了许多有用的信息,比如源程序文件位置,行号,类名,函数名等。具体的应用可以在具体的开发过程中添加、删除。

真机测试的时候,可以利用freopen将标准错误输出保存到指定的文件当中,这样就可以在问题发生后分析日志文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)redirectNSLogToDocumentFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // 真机测试时保存日志
    if ([CDeviceInfo getModelType] != SIMULATOR) {
        [self redirectNSLogToDocumentFolder];
    }

    .....
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics