使用場景
在某些時候,我們需要動態(tài)控制日志的打印級別。比如在執(zhí)行某個操作的時候,需要DDLogLevelVerbose級別,執(zhí)行完成后需要DDLogLevelInfo級別,這時候之前的日志級別設置就沒有能力來實現(xiàn).
之前的實現(xiàn)
#if DEBUG
static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
#else
static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
#endif
后面想到,是不是只要改變ddLogLevel的值就可以實現(xiàn)了呢?改成
#if DEBUG
static DDLogLevel ddLogLevel = DDLogLevelVerbose;
#else
static DDLogLevel ddLogLevel = DDLogLevelVerbose;
#endif
去掉了const修飾符,然后隨便在一個按鈕響應函數(shù)里面設置成
ddLogLevel = DDLogLevelError;
測試了下,點擊了按鈕,發(fā)現(xiàn)沒有作用,只能另外再找方法。
DDRegisteredDynamicLogging
后來在翻看DDLog.h文件時發(fā)現(xiàn)了DDRegisteredDynamicLogging這個協(xié)議,里面提供了2個靜態(tài)方法
+ (DDLogLevel)ddLogLevel;
+ (void)ddSetLogLevel:(DDLogLevel)level;
里面還有段說明文字:
Implement these methods to allow a file's log level
to be managed from a central location.
This is useful if you'd like to be able to change log levels for
various parts of your code from within the running application.
Imagine pulling up the settings for your application,
and being able to configure the logging level on a per file basis.
看樣子貌似可以,說干就干。新建一個類,實現(xiàn)DDRegisteredDynamicLogging協(xié)議。
DDDynamicLogLevel.h
#import "DDLog.h"
@interface DDDynamicLogLevel : NSObject <DDRegisteredDynamicLogging>
@end
DDDynamicLogLevel.m
<b>注意</b> 這里新建一個靜態(tài)變量,用于動態(tài)控制日志級別
static DDLogLevel s_ddLogLevel = DDLogLevelVerbose;
@implementation DDDynamicLogLevel
+ (DDLogLevel)ddLogLevel {
return s_ddLogLevel;
}
+ (void)ddSetLogLevel:(DDLogLevel)level {
s_ddLogLevel = level;
}
@end
然后將之前定義的日志級別宏定義替換為
#ifdef LOG_LEVEL_DEF
# undef LOG_LEVEL_DEF
#endif
#define LOG_LEVEL_DEF [DDDynamicLogLevel ddLogLevel]
注意引入頭文件DDDynamicLogLevel.h,再測試,
[DDDynamicLogLevel ddSetLogLevel:DDLogLevelError];
DDLogInfo(@"111 -- Info");
DDLogError(@"11111111");
[DDDynamicLogLevel ddSetLogLevel:DDLogLevelInfo];
DDLogInfo(@"222 -- Info");
DDLogError(@"222222222");
發(fā)現(xiàn)起作用了,打完收工~~~
結尾
就到這里了,祝大家使用愉快!