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

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

  • 博主:易飞扬
  • 原文链接 : http://www.yifeiyang.net/iphone-development-skills-of-the-debugging-chapter-2-save-the-log/
  • 转载请保留上面文字。

    大部分人调试程序都是看日志吧,这里我就给大家总结一下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];
        }
    
        .....
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值