1

I'd like to have a reusable logging method or function that spits out the name of the method it's called from. Example:

    - (void)exampleMethod {
        CustomLog(); //Outputs "exampleMethod"
    }
james_womack
  • 10,028
  • 6
  • 55
  • 74
  • Duplicate of http://stackoverflow.com/questions/1451342/objective-c-find-caller-of-method ? – David Gelhar Apr 21 '10 at 02:19
  • The question is a duplicate (didn't see that and yes I did search), but the answer provided to that question was not useful anyway. Two useful answers have been provided to this question below. Thanks for finding the dupe though. – james_womack Apr 21 '10 at 02:36

2 Answers2

2

Functions don't know about their calling environment (at least not in a useful way). The only way is to use a macro instead. Inside the macro, you have access to the self and _cmd arguments that hold the receiver and current selector, as well as the __PRETTY_FUNCTION__ macro that contains the human-readable name of the method as a C string.

Chuck
  • 234,037
  • 30
  • 302
  • 389
0

See How to print out the method name and line number and conditionally disable NSLog? for the inspiration for this answer and other useful NSLog tips. Here is what I desired:

//place in PCH file
#define ILog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

//use in any file in your project
ILog(@"test");// outputs -[AppDelegate applicationDidFinishLaunching:] [Line 38] test
Community
  • 1
  • 1
james_womack
  • 10,028
  • 6
  • 55
  • 74