iOS中控制NSLog输出时机

iOS 中如何将部分 Log 保存并上传?

1. 将全部的 log 写入本地文件
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 来进行输出

1
#define SLOG(fmt, ...) if (reportLoggerIsOpen) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

从宏定义可以看出,reportLoggerIsOpen 是控制 Log 输出的开关,对于reportLoggerIsOpen的定义,在 h 文件中先 extern 声明这个变量,然后再 m 文件中去实现。

1
2
3
4
5
.h 文件
#import <Foundation/Foundation.h>
extern BOOL reportLoggerIsOpen;

1
2
3
4
5
6
.m 文件
BOOL reportLoggerIsOpen = NO;
+ (void)setLogOpen:(BOOL)open {
reportLoggerIsOpen = open;
}

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

显示评论