Improved logging in Objective-C …

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.

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.

Table 2    Expressions for logging in Objective-C.

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值