对于基本的log输出,NSLog函数很方便,但它既不是有条件的,又不太容易定制。我们将创建一个log输出函数,它能对每次输出惊醒精准控制,还可以在非调试的配制下关闭输出。
多余的log输出会影响性能,还会减少设备的固态硬盘的寿命,
具体代码如下:
XYDebug.h#import#ifdef XYDEBUG#define XYLog(format...) XYDebug(__FILE__, __LINE__, format)#else#define XYLog(format...)#endifvoid XYDebug(const char *fileName, int lineNumber, NSString *fmt, ...);
XYDebug.m
#import "XYDebug.h"void XYDebug(const char *fileName, int lineNumber, NSString *fmt, ...){ va_list args; va_start(args, fmt); static NSDateFormatter *debugFormatter = nil; if (debugFormatter == nil) { debugFormatter = [[NSDateFormatter alloc] init]; [debugFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; } NSString *msg = [[NSString alloc] initWithFormat:fmt arguments:args]; NSString *filePath = [[NSString alloc] initWithUTF8String:fileName]; NSString *timestamp = [debugFormatter stringFromDate:[NSDate date]]; NSDictionary *info = [[NSBundle mainBundle] infoDictionary]; NSString *appName = [info objectForKey:(NSString *)kCFBundleNameKey]; fprintf(stdout, "%s %s[%s:%d] %s\n", [timestamp UTF8String], [appName UTF8String], [[filePath lastPathComponent] UTF8String], lineNumber, [msg UTF8String]); va_end(args); [msg release]; [filePath release];}使用方式:
在预编译文件中加入#import "XYDebug"
在build setting中设置如下图
将Debug设置成-DXYDEBUG。这个标志只添加在Debug配置中,而没有添加到Release配置中,这个标志会激活相应的XYLog宏定义,从而激活或禁用log输出。如果使用“Other C Flags”设定项目,一定要加上“-D”。
原文件 ——