前言
平時(shí)開(kāi)發(fā)調(diào)試時(shí)盼玄,通常采用NSLog打印相關(guān)信息,但是系統(tǒng)默認(rèn)不會(huì)打印這句log具體來(lái)自哪個(gè)位置器仗。為了提高定位代碼效率,我們經(jīng)常在log里加上一些特殊標(biāo)志符威鹿。如果系統(tǒng)能自動(dòng)打印log的位置轨香,不用我們自己特別處理,這樣不僅能提高開(kāi)發(fā)的效率弹沽,而且也能保持log格式的統(tǒng)一性策橘。
自定義log格式
下面是幾種自定義的log格式,輸出log所在的文件名丽已,方法名以及行數(shù)等信息。
#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 */
簡(jiǎn)單介紹以下幾個(gè)宏:
- VA_ARGS 是一個(gè)可變參數(shù)的宏,這個(gè)可變參數(shù)的宏是新的C99規(guī)范中新增的嘁灯,目前似乎只有g(shù)cc支持(VC6.0的編譯器不支持)丑婿。宏前面加上##的作用在于,當(dāng)可變參數(shù)的個(gè)數(shù)為0時(shí)羹奉,這里的##起到把前面多余的","去掉,否則會(huì)編譯出錯(cuò);
- FILE 宏在預(yù)編譯時(shí)會(huì)替換成當(dāng)前的源文件名迁筛;
- LINE宏在預(yù)編譯時(shí)會(huì)替換成當(dāng)前的行號(hào)耕挨;
- FUNCTION宏在預(yù)編譯時(shí)會(huì)替換成當(dāng)前的函數(shù)名稱。
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信息");
}
// 結(jié)果
[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信息