iOS中控制NSLog输出时机详解

2025-05-29 0 65
?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
-(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 文件

?

1

2

3

4

5

6

7

8

9
#import <Foundation/Foundation.h>

extern BOOL reportLoggerIsOpen;

.m 文件

BOOL reportLoggerIsOpen = NO;

+ (void)setLogOpen:(BOOL)open {

reportLoggerIsOpen = open;

}

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS中控制NSLog输出时机详解 https://www.kuaiidc.com/89827.html

相关文章

发表评论
暂无评论