iOS项目之使用开关控制日志输出的功能
https://www.cnblogs.com/sjxjjx/p/8907762.html
最近一直在做sdk的项目,用户提出了一个需求,需要屏蔽sdk内部的日志输出。由于sdk内部的日志是为了调试,如果屏蔽了肯定不方便,所以研究了一下日志输出开关的功能。
在这里介绍两种实现方案:一种方案是使用NSUserDefaults,一种方案是使用自定义类来控制。
第一种方案:NSUserDefaults
这种方案比较简单,主要使用NSUserDefaults来存储日志输出的状态。直接上代码:
[
](javascript:void(0); "复制代码")
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"> // 日志状态获取
[[[NSUserDefaults standardUserDefaults] valueForKey:@"kLogEnable"] boolValue]; // 日志状态修改
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
[userD setValue:@(s.isOn) forKey:@"kLogEnable"];
[userD synchronize];</pre>

](javascript:void(0); "复制代码")
然后在.pch文件中添加宏来进行判断输出日志功能:
[
](javascript:void(0); "复制代码")
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">#define customLogEnable [[[NSUserDefaults standardUserDefaults] valueForKey:@"kLogEnable"] boolValue]
define FirstMethodLog(format,...) if(customLogEnable) {\ NSLog((@"%s[%d]" format), FUNCTION, LINE, ##VA_ARGS);\
} else {}</pre>
[
](javascript:void(0); "复制代码")
这样在其他地方使用FirstMethodLog方法来输出日志,就可以实现控制日志输出的功能。
第二种方案:自定义日志输出管理类CustomLogManager
首先在.h文件中提供几个方法:
[
](javascript:void(0); "复制代码")
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">// 设置日志输出状态
- (void)setLogEnable:(BOOL)enable; // 获取日志输出状态
- (BOOL)getLogEnable; // 日志输出方法
- (void)customLogWithFunction:(const char *)function lineNumber:(int)lineNumber formatString:(NSString *)formatString;</pre>

](javascript:void(0); "复制代码")
然后在.m文件中,设置静态变量来存储日志输出状态值
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">// 默认值为NO
static BOOL kLogEnable = NO;</pre>
类方法的实现:
[
](javascript:void(0); "复制代码")
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">+ (void)setLogEnable:(BOOL)enable {
kLogEnable = enable;
} + (BOOL)getLogEnable { return kLogEnable;
} + (void)customLogWithFunction:(const char *)function lineNumber:(int)lineNumber formatString:(NSString *)formatString { if ([self getLogEnable]) { // 开启了Log
NSLog(@"%s[%d]%@", function, lineNumber, formatString);
}
}</pre>

](javascript:void(0); "复制代码")
最后添加宏定义
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">#define SecondMethodLog(format,...) [CutomLogManager customLogWithFunction:FUNCTION lineNumber:LINE formatString:[NSString stringWithFormat:format, ##VA_ARGS]]</pre>
这样在其他地方使用SecondMethodLog方法来输出日志,就可以控制日志输出了。