NSLog 的优化
打印日志,是任何开发常用的调试手段。在ios系统提供了打印日志的API The utility functions NSLog() and NSLogv() use the NSString string formatting services to log error messages. Note that as a consequence of this, you should take care when specifying the argument for these functions. A common mistake is to specify a string that includes formatting characters, as shown in the following example.
但是NSLog 很占用性能,如果在release版本上仍然使用了NSLog 会极大的降低性能。通常的做法是
#ifndef DEBUG
#define AZLog(fmt, ...) NSLog((@"[文件名:%s]\n" "[函数名:%s]\n" "[行号:%d] \n" fmt"\n\n"), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define AZLog(...)
#endif
但是 一个项目 是很多人一起写的,每个模块可能 需要打印的日志不一样,或者说,张三写代码的时候,不想看见李四负责模块的打印日志。怎么办?
typedef enum _LogOwner
{
Log_All =0,
Log_LW =1,
Log_SYX =2,
Log_Andrew =3,
}LogOwner;
#ifdef TEST_ENV_PRODUCTION
#define CTLogBase(owner,onwer_type,fmt,...)
#elif defined TEST_ENV_QA
#define CTLogBase(owner,onwer_type,fmt,...) if ([[CTLog defaultCTLog].owners containsObject:[NSNumber numberWithInteger:Log_All]] || [[CTLog defaultCTLog].owners containsObject:[NSNumber numberWithInteger:onwer_type]])\
{\
NSLog((@"%s [owner: %@] [line: %d] " fmt),__FUNCTION__, owner,__LINE__, ##__VA_ARGS__);\
}\
#endif
// NSLog((@"[文件名:%s]" "[函数名:%s]" "[行号:%d]" format), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);
#define LWLog(fmt,...) CTLogBase(@"LW",Log_LW,fmt,##__VA_ARGS__)
#define SYXLog(fmt,...) CTLogBase(@"SYX",Log_SYX,fmt,##__VA_ARGS__)
#define AZLog(fmt,...) CTLogBase(@"Andrew",Log_Andrew,fmt,##__VA_ARGS__)
其中 CTLog类为:
//
// CTLog.h
// circle_iphone
//
// Created by Andrew on 15/11/30.
// Copyright © 2015年 ctquan. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* 调试辅助类
*/
@interface CTLog : NSObject
@property (nonatomic,strong)NSMutableArray *owners;
#pragma mark - 对外接口
+(instancetype)defaultCTLog;
/** 只显示该开发者的调试日志 */
-(void)setLogOwner:(LogOwner)owner;
@end
//
// CTLog.m
// circle_iphone
//
// Created by Andrew on 15/11/30.
// Copyright © 2015年 ctquan. All rights reserved.
//
#import "CTLog.h"
@implementation CTLog
+(instancetype)defaultCTLog
{
static CTLog *ctlog=nil;
static dispatch_once_t once_log;
dispatch_once(&once_log, ^{
ctlog=[CTLog new];
[ctlog InitArray];
});
return ctlog;
}
-(void)InitArray
{
_owners=[NSMutableArray array];
[_owners addObject:[NSNumber numberWithInteger:Log_All]];
}
/** 只显示该开发者的调试日志 */
-(void)setLogOwner:(LogOwner)owner
{
[_owners removeAllObjects];
[_owners addObject:[NSNumber numberWithInteger:owner]];
}
@end
在appdelegate.m 中 :
// 启动调试日志
[CTLog defaultCTLog];
// 只显示该开发者的调试日志
[[CTLog defaultCTLog] setLogOwner:Log_All];