自定義可配置開關(guān)的NSLog
最近公司要求封裝一套打包成 .a 靜態(tài)庫的SDK,需要在SDK中輸出一些Log信息。
參考友盟对人、JPush等SDK寫法,想給Log配置一個(gè)開關(guān),方便使用SDK時(shí)可以控制打開或關(guān)閉Log輸出搪柑。
以下是SDK只提供 .a 靜態(tài)庫時(shí)的一種解決思路:
#import <Foundation/Foundation.h>
/**
* 自定義Log,可配置開關(guān)(用于替換NSLog)
*/
#define KDS_Log(format,...) CustomLog(__FUNCTION__,__LINE__,format,##__VA_ARGS__)
/**
* 自定義Log
* @warning 外部可直接調(diào)用 KDS_Log
*
* @param func 方法名
* @param lineNumber 行號
* @param format Log內(nèi)容
* @param ... 個(gè)數(shù)可變的Log參數(shù)
*/
void CustomLog(const char *func, int lineNumber, NSString *format, ...);
/**
* 自定義Log類索烹,外部控制Log開關(guān)
*/
@interface KDS_CustomLog : NSObject
/**
* Log 輸出開關(guān) (默認(rèn)關(guān)閉)
*
* @param flag 是否開啟
*/
+ (void)setLogEnable:(BOOL)flag;
/**
* 是否開啟了 Log 輸出
*
* @return Log 開關(guān)狀態(tài)
*/
+ (BOOL)logEnable;
@end
#import "KDS_CustomLog.h"
// Log 開關(guān)狀態(tài)工碾,默認(rèn)不輸出log信息
static BOOL KDS_Log_Switch = NO;
@implementation KDS_CustomLog
void CustomLog(const char *func, int lineNumber, NSString *format, ...)
{
if ([KDS_CustomLog logEnable]) { // 開啟了Log
va_list args;
va_start(args, format);
NSString *string = [[NSString alloc] initWithFormat:format arguments:args];
NSString *strFormat = [NSString stringWithFormat:@"%s, Line:%i, SDK_Log:%@",func,lineNumber,string];
NSLogv(strFormat, args);
va_end(args);
}
}
+ (BOOL)logEnable {
return KDS_Log_Switch;
}
+ (void)setLogEnable:(BOOL)flag {
KDS_Log_Switch = flag;
}
@end
以下是調(diào)用方式:
#import "KDS_CustomLog.h"
- (void)logTest
{
[KDS_CustomLog setLogEnable:YES];
KDS_Log(@"打開");
NSLog(@"%d",[KDS_CustomLog logEnable]);
[KDS_CustomLog setLogEnable:NO];
KDS_Log(@"關(guān)閉");
NSLog(@"%d",[KDS_CustomLog logEnable]);
[KDS_CustomLog setLogEnable:YES];
KDS_Log(@"打開");
NSLog(@"%d",[KDS_CustomLog logEnable]);
}
和控制臺輸出結(jié)果:
輸出結(jié)果.png
(如果有任何問題,歡迎指出0傩铡)