具体请参考:
- NSLog the method name with objective-C in iPhone
- How to print out the method name and line number and conditionally disable NSLog?
- How can I add context information - such as the current method or line number - to my logging statements?
获取方法名:
NSLog(@"%@", NSStringFromSelector(_cmd))
获取当前的方法名和当前的行号,可以使用__func__
和__LINE__
, 如下:
NSLog(@"%s:%d someObject=%@", __func__, __LINE__, someObject);
Preprocessor macros for logging
Macro | Format | Description |
---|---|---|
__func__ | %s | Current function signature |
__LINE__ | %d | Current line number |
__FILE__ | %s | Full path to source file |
__PRETTY_FUNCTION__ | %s | Like __func__ , but includes verbose type information in C++ code. |
Expressions for logging
Expression | Format | Description |
---|---|---|
NSStringFromSelector(_cmd) | %@ | Name of the current selector |
NSStringFromClass([self class]) | %@ | Current object’s class name |
[[NSString stringWithUTF8String:__FILE__ ] lastPathComponent] | %@ | Source code file name |
[NSThread callStackSymbols] | %@ | NSArray of stack trace |
自定义NSLog输出:
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
# define DLog(...)
#endif
// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
或者
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...)
#endif
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#ifdef DEBUG
# define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; }
#else
# define ULog(...)
#endif