Technical Q&A QA1669

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: The C preprocessor provides a number of standard macros that give you information about the current file, line number, or function. Additionally, Objective-C has the _cmd implicit argument which gives the selector of the current method, and functions for converting selectors and classes to strings. You can use these in your NSLog statements to provide useful context during debugging or error handling.

Listing 1  Example of logging the current method and line number. Paste it into your project, and see what it prints!

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.

Table 1  Preprocessor macros and for logging in C/C++/Objective-C.


Format Specifier




Current function signature.



Current line number in the source code file.



Full path to the source code file.



Like __func__, but includes verbose type information in C++ code.

Table 2  Expressions for logging in Objective-C.


Format Specifier




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


Expanded logging examples.


New document that describes use of preprocessor macros and Objective-C language features to provide better context in log statements.