(20160604) CocoaLumberjack and cocoalumberjack for open-source third-party Learning

Source: Internet
Author: User

(20160604) CocoaLumberjack and cocoalumberjack for open-source third-party Learning

CocoaLumberjack is a useful log printing tool that can help us print the log information in the project to the terminal or output it to the file.

Address: https://github.com/CocoaLumberjack/CocoaLumberjack

Class diagram:

 

 

 

I. Use of plug-ins

Because CocoaLumberjack has been introduced in detail on the Internet, some of the content is sorted out from the use of the network in conjunction with the project;

1.1: DDLog output type

DDLog: basic class, which must be introduced. DDASLLogger: supports writing debugging statements to Apple logs. Generally, it is being developed for Mac. Optional. DDTTYLogger: supports writing debugging statements to the xCode console. Even if we use it. Optional. DDFileLogger: supports writing debugging statements to the file system. Optional.

1.2: DDLog Log Level type

DDLogError: defines the output error text DDLogWarn: defines the output warning text DDLogInfo: defines the output information text DDLogDebug: defines the output debugging text DDLogVerbose: defines the log level provided by the output detailed text: LOG_LEVEL_ERROR: only error logs are displayed. LOG_LEVEL_WARN: including: LOG_LEVEL_ERRORLOG_LEVEL_INFO: including: LOG_LEVEL_WARNLOG_LEVEL_DEBUG: including: LOG_LEVEL_INFOLOG_LEVEL_VERBOSE: includes: logging: disabling logs

1.3: set different levels of colors

[[DDTTYLogger sharedInstance] setColorsEnabled: YES]; // enable color discrimination [[DDTTYLogger sharedInstance] setForegroundColor: [UIColor whiteColor] backgroundColor: [UIColor grayColor] forFlag: enabled]; // set the text to white and the background to Gray. [[DDTTYLogger sharedInstance] Background: [UIColor redColor] backgroundColor: [UIColor whiteColor] forFlag: DDLogFlagDebug]; [[DDTTYLogger sharedInstance] Background: [UIColor cyanColor] backgroundColor: [UIColor blueColor] forFlag: DDLogFlagInfo]; [[DDTTYLogger sharedInstance] Priority: [UIColor lightGrayColor] backgroundColor: [UIColor orangeColor] forFlag: Priority]; [shard sharedInstance] Priority: [UIColor whiteColor] backgroundColor: [UIColor redColor] forFlag: DDLogFlagError];

Note: The display color is the pointer to the XCode console output display, but also combined with the plug-in XcodeColors (Address: https://github.com/robbiehanson/XcodeColors); then add the following setenv code, it is positioned above, otherwise, it will be ineffective;

setenv("XcodeColors", "YES", 0);[DDLog addLogger:[DDTTYLogger sharedInstance]];

1.4: Set the output log format

Because we want to get more information during output, DDLog can customize a format to obtain log details. The following class is used in our project:

ZULoggerFormatter * formatter = [[ZULoggerFormatter alloc] init]; [[DDTTYLogger sharedInstance] setLogFormatter: formatter]; // It is currently displayed on the DDTTYLogger type and can be added to the input file

Format: ZULoggerFormatter

@interface ZULoggerFormatter: NSObject<DDLogFormatter>@end#import "ZULoggerFormatter.h"#import "NSDate+Utilities.h"@implementation ZULoggerFormatter {}- (NSString *)formatLogMessage:(DDLogMessage *)logMessage {  NSString *logLevel = nil;  switch (logMessage.flag) {    case DDLogFlagError:      logLevel = @"[ERROR]";      break;    case DDLogFlagWarning:      logLevel = @"[WARN]";      break;    case DDLogFlagInfo:      logLevel = @"[INFO]";      break;    case DDLogFlagDebug:      logLevel = @"[DEBUG]";      break;    default:      logLevel = @"[VBOSE]";      break;  }  NSString *formatStr      = [NSString stringWithFormat:@"%@ %@ [%@][line %ld] %@ %@", logLevel, [logMessage.timestamp stringWithFormat:@"yyyy-MM-dd HH:mm:ss.S"], logMessage.fileName, logMessage.line, logMessage.function, logMessage.message];  return formatStr;}@end

1.5 set macros to replace NSLog

#if Product || Local#define NSLog(...) DDLogVerbose(__VA_ARGS__)#define Log(...) DDLogVerbose(__VA_ARGS__)#else#define NSLog(...) {}#define Log(...) {}#endif#define LogError(...) DDLogError(__VA_ARGS__)

In this way, you can replace the nslogs in the project with errors at the DDLogVerbose level;

1.6 set log output levels in different environments

#if Product ||Localstatic const int ddLogLevel = LOG_LEVEL_VERBOSE;#elsestatic const int ddLogLevel = LOG_LEVEL_ERROR;#endif

1.7 set output to file

- (DDFileLogger *)fileLogger{    if (!_fileLogger) {        DDFileLogger *fileLogger = [[DDFileLogger alloc] init];        fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling        fileLogger.logFileManager.maximumNumberOfLogFiles = 7;                _fileLogger = fileLogger;    }    return _fileLogger;}

If it is not set, it provides the corresponding default value:

Unsigned long const kdddefadefalogmaxfilesize = 1024*1024; // 1 MB one file size NSTimeInterval const Limit = 60*60*24; // 24 Hours one day NSUInteger const kdddefadefalogmaxnumlogfiles = 5; // 5 Files five unsigned long const kdddefaloglogfilesdiskquota = 20*1024*1024; // 20 MB total

If there is a storage path (you can set paths ):

NSString *appName = [[NSProcessInfo processInfo] processName];NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);NSString *basePath = ([paths count] > 0) ? paths[0] : NSTemporaryDirectory();NSString *logsDirectory = [[basePath stringByAppendingPathComponent:@"Logs"] stringByAppendingPathComponent:appName];

1.8 share the log management class used by the Project

# Import <Foundation/Foundation. h> # import <CocoaLumberjack. h> # import "ZULoggerFormatter. h "@ interface MyFileLogger: NSObject @ property (nonatomic, strong, readwrite) DDFileLogger * fileLogger; + (MyFileLogger *) sharedManager; @ end # import" MyFileLogger. h "@ implementation MyFileLogger # pragma mark-Inititlization-(instancetype) init {self = [super init]; if (self) {[self configureLogging];} return self ;}# Pragma mark Singleton Mode static MyFileLogger * sharedManager = nil; + (MyFileLogger *) sharedManager {static dispatch_once_t once; dispatch_once (& once, ^ {sharedManager = [[self alloc] init] ;}); return sharedManager ;}# pragma mark-Configuration-(void) configureLogging {setenv ("XcodeColors", "YES ", 0); [DDLog addLogger: [DDASLLogger sharedInstance]; [DDLog addLogger: [DDTTYLogger sharedInstance]; [[DDTTYLogger sha RedInstance] setColorsEnabled: YES]; [[DDTTYLogger sharedInstance] usage: [UIColor blueColor] backgroundColor: nil forFlag: DDLogFlagInfo]; [[shard sharedInstance] usage: [UIColor purpleColor] backgroundColor: nil forFlag: DDLogFlagDebug]; [[DDTTYLogger sharedInstance] setForegroundColor: [UIColor redColor] backgroundColor: nil forFlag: DDLogFlagError]; [DDTTYLogger sharedIn Stance] identifier: [UIColor greenColor] backgroundColor: nil forFlag: identifier]; ZULoggerFormatter * formatter = [[ZULoggerFormatter alloc] init]; [[DDTTYLogger sharedInstance] setLogFormatter: formatter]; [DDLog addLogger: self. fileLogger] ;}# pragma mark-Getters-(DDFileLogger *) fileLogger {if (! _ FileLogger) {DDFileLogger * fileLogger = [[DDFileLogger alloc] init]; fileLogger. rollingFrequency = 60*60*24; // 24 hour rolling fileLogger. logFileManager. maximumNumberOfLogFiles = 7; _ fileLogger = fileLogger;} return _ fileLogger;} @ end

 

Ii. knowledge points

2.1 For the set of level inclusion, DDLogLevelAll displays all, and base it displays each other in descending order. You can use this code to understand the enumeration settings;

typedef NS_OPTIONS(NSUInteger, DDLogFlag){    /**     *  0...00001 DDLogFlagError     */    DDLogFlagError      = (1 << 0),        /**     *  0...00010 DDLogFlagWarning     */    DDLogFlagWarning    = (1 << 1),        /**     *  0...00100 DDLogFlagInfo     */    DDLogFlagInfo       = (1 << 2),        /**     *  0...01000 DDLogFlagDebug     */    DDLogFlagDebug      = (1 << 3),        /**     *  0...10000 DDLogFlagVerbose     */    DDLogFlagVerbose    = (1 << 4)};/** *  Log levels are used to filter out logs. Used together with flags. */typedef NS_ENUM(NSUInteger, DDLogLevel){    /**     *  No logs     */    DDLogLevelOff       = 0,        /**     *  Error logs only     */    DDLogLevelError     = (DDLogFlagError),        /**     *  Error and warning logs     */    DDLogLevelWarning   = (DDLogLevelError   | DDLogFlagWarning),        /**     *  Error, warning and info logs     */    DDLogLevelInfo      = (DDLogLevelWarning | DDLogFlagInfo),        /**     *  Error, warning, info and debug logs     */    DDLogLevelDebug     = (DDLogLevelInfo    | DDLogFlagDebug),        /**     *  Error, warning, info, debug and verbose logs     */    DDLogLevelVerbose   = (DDLogLevelDebug   | DDLogFlagVerbose),        /**     *  All logs (1...11111)     */    DDLogLevelAll       = NSUIntegerMax};

Add corresponding macro for processing

#define NSLogError(frmt, ...)    do{ if(DD_NSLOG_LEVEL >= 1) NSLog((frmt), ##__VA_ARGS__); } while(0)#define NSLogWarn(frmt, ...)     do{ if(DD_NSLOG_LEVEL >= 2) NSLog((frmt), ##__VA_ARGS__); } while(0)#define NSLogInfo(frmt, ...)     do{ if(DD_NSLOG_LEVEL >= 3) NSLog((frmt), ##__VA_ARGS__); } while(0)#define NSLogDebug(frmt, ...)    do{ if(DD_NSLOG_LEVEL >= 4) NSLog((frmt), ##__VA_ARGS__); } while(0)#define NSLogVerbose(frmt, ...)  do{ if(DD_NSLOG_LEVEL >= 5) NSLog((frmt), ##__VA_ARGS__); } while(0)

2.2: Process NSProcessInfo Method

+ (NSProcessInfo *) processInfo // return the information of the current process-(NSArray *) arguments // return the parameters of the current process in the form of an NSString object array-(NSDictionary *) environment // return the dictionary of variables/value pairs to describe the current environment variables (such as PATH and HOME) and their values-(int) processIdentifier // return the process identifier, it is a unique number assigned to a process by the operating system. It is used to identify each running process-(NSString *) processName // return the name of the currently running process-(NSString *) globallyUniqueString // each time this method is called, different single-value strings are returned. You can use this string to generate a temporary Single-value File Name-(NSString *) hostname // return the host system name (in the author's Mac OS x system, the returned mac-mato-ipad.l Ocal)-(NSUInteger) operatingSystem // return the number representing the Operating System (5 is returned in the author's Mac OS x System)-(NSString *) operatingSystemName // return the name of the Operating System (NSMACHOperatingSystem is returned in the author's Mac OS x system. The value may be defined in NSProgressInfo. in the hfile)-(NSString *) operatingSystemVersionString // return the current Version of the operating system (the author returns Version 10.7.5 (Build 11G56) in Mac OS x)-(void) setProcessName :( NSString *) name // set the current process name to name. This method should be used with caution. There should be some assumptions about the process name (such as the user's default settings)
For example, NSString * appName = [[NSProcessInfo processInfo] processName];

2.3: lengthOfBytesUsingEncoding: NSUTF8StringEncoding

It is used to calculate the length of a string containing Chinese and English characters. When the preceding method is used, it is converted into three bytes, the other one. int len = [textField. text lengthOfBytesUsingEncoding: NSUTF8StringEncoding];

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.