虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > IOS编程/Objective-C > iOS中控制NSLog输出时机详解

iOS中控制NSLog输出时机详解
类别:IOS编程/Objective-C   作者:码皇   来源:互联网   点击:

本文给大家介绍的是iOS开发中关于nslog的输出时机的相关内容,非常简单实用,有需要的小伙伴可以参考下
    -(void)saveDEBUGlog{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"testLog_%@.log",currentDateStr];
    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);
    }

这个方法主要是调用 freopen 这个方法来写入, 其中 stdout 和 stderr 囊括了 iOS 大部分的异常输出。

2. 根据 Bool 值控制 log 输出

用户在使用 app 遇到各种各样的问题,当自己以及测试团队不好定位原因的时候,能将用户把关键点的 log 发送过来是最好的分析方法了。但是如何将 app 运行过程中的 log 截取一部分保存呢?像开关一样能够控制 log 的读写呢?通过阅读 MQTTLog 源码发现获得的灵感。

首先对 NSLog 进行下宏替换,项目中统一使用 SLOG 来进行输出

#define SLOG(fmt, ...) if (reportLoggerIsOpen) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
从宏定义可以看出,reportLoggerIsOpen 是控制 Log 输出的开关,对于reportLoggerIsOpen的定义,在 h 文件中先 extern 声明这个变量,然后再 m 文件中去实现。

.h 文件

    #import <Foundation/Foundation.h>extern BOOL reportLoggerIsOpen;
    .m 文件BOOL reportLoggerIsOpen = NO;
    + (void)setLogOpen:(BOOL)open {
    reportLoggerIsOpen = open;
    }

通过 setLogOpen 这个方法,就能够收放自如的控制日志写入了。比如你需要抓取登录模块的日志,那么就在登录前传入 true,登录完毕后,传入 false,即可只保留登录模块的日志了。

您可能感兴趣的文章:

  • iOS中捕获日志与异常示例详解
  • IOS本地日志记录解决方案
  • iOS中日志同步获取NSLog重定向以及其他详解
相关热词搜索: IOS中NSLog输出 iOS NSLog IOS开发 NSLog使