Improved logging in Objective-C
Q: How can I add context information - such as
the current method or line number - to my logging statements?
A: _cmd
NSLog
Listing 1
NSMutableArray *someObject = [NSMutableArray array]; |
NSLog(@"%s:%d someObject=%@", __func__, __LINE__, someObject); |
[someObject addObject:@"foo"]; |
NSLog(@"%s:%d someObject=%@", __func__, __LINE__, someObject); |
The following tables list the most popular macros and expressions which might be useful in your logging statements.
Macro |
Format Specifier |
Description |
---|---|---|
__func__ |
%s |
Current function signature. |
__LINE__ |
%d |
Current line number in the source code file. |
__FILE__ |
%s |
Full path to the source code file. |
__PRETTY_FUNCTION__ |
%s |
Like __func__, but includes verbose type information in C++ code. |
Expression |
Format Specifier |
Description |
---|---|---|
NSStringFromSelector(_cmd) |
%@ |
Name of the current selector. |
NSStringFromClass([self class]) |
%@ |
Name of the current object's class. |
[[NSString stringWithUTF8String:__FILE__] lastPathComponent] |
%@ |
Name of the source code file. |
[NSThread callStackSymbols] |
%@ |
NSArray of the current stack trace as programmer-readable strings. For debugging only, do not present it to end users or use to do any logic in your program. |
Document Revision History
Date | Notes |
---|---|
2011-10-04 |
Expanded logging examples. |
2009-10-27 |
New document that describes use of preprocessor macros and Objective-C language features to provide better context in log statements. |
© 2011 Apple Inc. All Rights Reserved. (Last updated: 2011-10-04)