自定义log格式

2019-05-11  本文已影响0人  黄定师

前言

平时开发调试时,通常采用NSLog打印相关信息,但是系统默认不会打印这句log具体来自哪个位置。为了提高定位代码效率,我们经常在log里加上一些特殊标志符。如果系统能自动打印log的位置,不用我们自己特别处理,这样不仅能提高开发的效率,而且也能保持log格式的统一性。

自定义log格式

下面是几种自定义的log格式,输出log所在的文件名,方法名以及行数等信息。


#ifndef PrefixHeader_pch

#define PrefixHeader_pch

// Include any system framework and library headers here that should be included in all compilation units.

// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.

#ifdef __OBJC__


#if DEBUG

#define HLog(format, ...) fprintf(stderr,"[%s] %s:%d\t%s\n", __TIME__, [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:format, ##__VA_ARGS__] UTF8String])

#else

#define HLog(format, ...) nil

#endif


#ifdef DEBUG

#define DLog(format, ...) printf("[%s] %s [第%d行] %s\n", __TIME__, __FUNCTION__, __LINE__, [[NSString stringWithFormat:format, ## __VA_ARGS__] UTF8String])

#else

#define DLog(format, ...)

#endif


#if DEBUG

#define SLog(format, ...) NSLog(@"%s [第%d行] %@", __FUNCTION__, __LINE__,format, ##__VA_ARGS__)

#else

#define SLog(format, ...) nil

#endif


#endif

#endif /* PrefixHeader_pch */

简单介绍以下几个宏:

  1. VA_ARGS 是一个可变参数的宏,这个可变参数的宏是新的C99规范中新增的,目前似乎只有gcc支持(VC6.0的编译器不支持)。宏前面加上##的作用在于,当可变参数的个数为0时,这里的##起到把前面多余的","去掉,否则会编译出错;
  2. FILE 宏在预编译时会替换成当前的源文件名;
  3. LINE宏在预编译时会替换成当前的行号;
  4. FUNCTION宏在预编译时会替换成当前的函数名称。

log打印示例

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    HLog(@"我是HLog信息");
    
    DLog(@"我是DLog信息");
    
    SLog(@"我是SLog信息");
    
    NSLog(@"我是NSLog信息");
}

// 结果
[22:18:58] ViewController.m:30  我是HLog信息
[22:18:58] -[ViewController viewDidLoad] [第32行] 我是DLog信息
2019-05-11 22:19:07.130070+0800 FMDB[5218:589287] -[ViewController viewDidLoad] [第34行] 我是SLog信息
2019-05-11 22:19:07.130227+0800 FMDB[5218:589287] 我是NSLog信息
上一篇 下一篇

猜你喜欢

热点阅读