代码直接上:
typedef NS_OPTIONS(unsigned char, YJLogLevel){
YJLog_None = 0,
YJLog_Error = 1 << 0,
YJLog_Warn = 1 << 1,
YJLog_Debug = 1 << 2,
YJLog_Info = 1 << 3,
};
#ifdef DEBUG
#define LOGD(...) [[YJLog sharedInstance] output:YJLog_Debug fmt:__VA_ARGS__];
#define LOGW(...) [[YJLog sharedInstance] output:YJLog_Warn fmt:__VA_ARGS__];
#define LOGE(...) [[YJLog sharedInstance] output:YJLog_Error fmt:__VA_ARGS__];
#define LOGI(...) [[YJLog sharedInstance] output:YJLog_Info fmt:__VA_ARGS__];
//带行号 函数名的实现
#define _LOGD(...) [[YJLog sharedInstance] output:YJLog_Debug funcName:__func__ line:__LINE__ fmt:__VA_ARGS__];
#define _LOGW(...) [[YJLog sharedInstance] output:YJLog_Warn funcName:__func__ line:__LINE__ fmt:__VA_ARGS__];
#define _LOGE(...) [[YJLog sharedInstance] output:YJLog_Error funcName:__func__ line:__LINE__ fmt:__VA_ARGS__];
#define _LOGI(...) [[YJLog sharedInstance] output:YJLog_Info funcName:__func__ line:__LINE__ fmt:__VA_ARGS__];
#else
#define LOGD(...)
#define LOGW(...)
#define LOGE(...)
#define LOGI(...)
#define _LOGD(...)
#define _LOGW(...)
#define _LOGE(...)
#define _LOGI(...)
//#define NSLog(...) LOGD(...)
#endif
@interface YJLog : NSObject
+(instancetype)sharedInstance;
-(void)output:(YJLogLevel)level fmt:(NSString *)fmt, ...;
-(void)output:(YJLogLevel)level funcName:(const char *)funcName line:(int)line fmt:(NSString *)fmt, ...;
/**
* 默认输出全部log
*/
@property(atomic, assign)YJLogLevel logLevel;
@end
@implementation YJLog
+(instancetype)sharedInstance
{
static YJLog *obj = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
obj = [[self alloc] init];
obj.logLevel = 0;
});
return obj;
}
-(void)output:(YJLogLevel)level fmt:(NSString *)fmt, ...
{
if (!fmt || ![fmt isKindOfClass:[NSString class]])
return;
else{
if (!(_logLevel&level))
return;
else{
va_list args;
va_start(args, fmt);
NSString *log = [[NSString alloc] initWithFormat:fmt arguments:args];
fprintf(stdout, "[%s] %s\n", [[self level2String:level] UTF8String], [log UTF8String]);
va_end(args);
}
}
}
-(void)output:(YJLogLevel)level funcName:(const char *)funcName line:(int)line fmt:(NSString *)fmt, ...
{
if (!fmt || ![fmt isKindOfClass:[NSString class]])
return;
else{
if (!(_logLevel&level))
return;
else{
va_list args;
va_start(args, fmt);
NSString *log = [[NSString alloc] initWithFormat:fmt arguments:args];
fprintf(stdout, "[%s %s %d] %s\n", [[self level2String:level] UTF8String], funcName, line, [log UTF8String]);
va_end(args);
}
}
}
-(NSString *)level2String:(YJLogLevel)level
{
if (level == YJLog_None) return @"YJLog_None";
if (level == YJLog_Error) return @"YJLog_Error";
if (level == YJLog_Warn) return @"YJLog_Warn";
if (level == YJLog_Debug) return @"YJLog_Debug";
if (level == YJLog_Info) return @"YJLog_Info";
return @"Undefined";
}