使用場景
在某些時(shí)候,我們需要?jiǎng)討B(tài)控制日志的打印級(jí)別堰燎。比如在執(zhí)行某個(gè)操作的時(shí)候蜜暑,需要DDLogLevelVerbose
級(jí)別褐啡,執(zhí)行完成后需要DDLogLevelInfo
級(jí)別,這時(shí)候之前的日志級(jí)別設(shè)置就沒有能力來實(shí)現(xiàn).
之前的實(shí)現(xiàn)
#if DEBUG
static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
#else
static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
#endif
后面想到,是不是只要改變ddLogLevel
的值就可以實(shí)現(xiàn)了呢?改成
#if DEBUG
static DDLogLevel ddLogLevel = DDLogLevelVerbose;
#else
static DDLogLevel ddLogLevel = DDLogLevelVerbose;
#endif
去掉了const
修飾符,然后隨便在一個(gè)按鈕響應(yīng)函數(shù)里面設(shè)置成
ddLogLevel = DDLogLevelError;
測試了下啄栓,點(diǎn)擊了按鈕,發(fā)現(xiàn)沒有作用也祠,只能另外再找方法昙楚。
DDRegisteredDynamicLogging
后來在翻看DDLog.h
文件時(shí)發(fā)現(xiàn)了DDRegisteredDynamicLogging
這個(gè)協(xié)議,里面提供了2個(gè)靜態(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.
看樣子貌似可以诈嘿,說干就干堪旧。新建一個(gè)類,實(shí)現(xiàn)DDRegisteredDynamicLogging
協(xié)議奖亚。
DDDynamicLogLevel.h
#import "DDLog.h"
@interface DDDynamicLogLevel : NSObject <DDRegisteredDynamicLogging>
@end
DDDynamicLogLevel.m
<b>注意</b> 這里新建一個(gè)靜態(tài)變量淳梦,用于動(dòng)態(tài)控制日志級(jí)別
static DDLogLevel s_ddLogLevel = DDLogLevelVerbose;
@implementation DDDynamicLogLevel
+ (DDLogLevel)ddLogLevel {
return s_ddLogLevel;
}
+ (void)ddSetLogLevel:(DDLogLevel)level {
s_ddLogLevel = level;
}
@end
然后將之前定義的日志級(jí)別宏定義替換為
#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)起作用了爆袍,打完收工~~~
結(jié)尾
就到這里了,祝大家使用愉快作郭!