搜索
您的当前位置:首页正文

CocoaLumberjack:简单好用的Log库

来源:二三娱乐

CocoaLumberjack是一个可以在iOS和Mac开发中使用的日志库,强大又不失灵活。集成进项目后,配置下,然后用DDLog语句简单地取代NSLog语句( DDLog的使用方法和NSLog一样)就可以啦,是不是很方便。

安装

platform:ios, '7.0'
target 'CocoaLumberjackDemo' do
pod 'CocoaLumberjack'
end
github "CocoaLumberjack/CocoaLumberjack"

使用

CocoaLumberjack自带了几种Log方式:

1.DDLog(整个框架的基础)
2.DDASLLogger(发送日志语句到苹果的日志系统,以便它们显示在Console.app上)
3.DDTTYLoyger(发送日志语句到Xcode控制台)
4.DDFIleLoger(把日志写入本地文件)

你可以同时记录文件和控制台,还可以创建自己的logger,将日志语句发送到网络或者数据库中。

使用的时候需要引入头文件:#import <CocoaLumberjack/CocoaLumberjack.h>,你还需要全局设置下log级别:static const DDLogLevel ddLogLevel = DDLogLevelDebug;,关于Log级别,下面会细讲。

所以你的.pch里面可能有段这样的代码:

PrefixHeader.pch

然后加入代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 添加DDASLLogger,你的日志语句将被发送到Xcode控制台
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    
    // 添加DDTTYLogger,你的日志语句将被发送到Console.app
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    
    // 添加DDFileLogger,你的日志语句将写入到一个文件中,默认路径在沙盒的Library/Caches/Logs/目录下,文件名为bundleid+空格+日期.log。
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    fileLogger.rollingFrequency = 60 * 60 * 24;
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];
    
    //产生Log
    DDLogVerbose(@"Verbose");
    DDLogDebug(@"Debug");
    DDLogInfo(@"Info");
    DDLogWarn(@"Warn");
    DDLogError(@"Error");
    
    return YES;
}

DDLog和NSLog的语法是一样的。

运行程序,可以在Xocde控制台看到:


Xcode日志

产生的Log文件打开是这样的:


Log文件

Log级别

接下来,你就要考虑用哪种级别了,CocoaLumberjack有5种:

typedef NS_OPTIONS(NSUInteger, DDLogFlag){
    DDLogFlagError      = (1 << 0),
    DDLogFlagWarning    = (1 << 1),
    DDLogFlagInfo       = (1 << 2),
    DDLogFlagDebug      = (1 << 3),
    DDLogFlagVerbose    = (1 << 4)
};

Log Level 用来过滤每条Log:

typedef NS_ENUM(NSUInteger, DDLogLevel){
    DDLogLevelOff       = 0,
    DDLogLevelError     = (DDLogFlagError),
    DDLogLevelWarning   = (DDLogLevelError   | DDLogFlagWarning),
    DDLogLevelInfo      = (DDLogLevelWarning | DDLogFlagInfo),
    DDLogLevelDebug     = (DDLogLevelInfo    | DDLogFlagDebug),
    DDLogLevelVerbose   = (DDLogLevelDebug   | DDLogFlagVerbose),
    DDLogLevelAll       = NSUIntegerMax
};

例如,如果您将日志级别设置为 LOG_LEVEL_INFO,那么你会看到error、Warn和Info语句。

我们也可以为Debug和Release模式设置不同的Log级别:

#ifdef DEBUG 
static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
#else 
static const DDLogLevel ddLogLevel = DDLogLevelWarning;
#endif

我们还可以为每种loger设置不同的级别:

[DDLog addLogger:[DDASLLogger sharedInstance] withLevel:DDLogLevelInfo];
[DDLog addLogger:[DDTTYLogger sharedInstance] withLevel:DDLogLevelDebug];

我们还可以自定义Logger,实现我们自己想要的处理,具体可以看他的文档。

Top