views:

42

answers:

2

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"
    }
+1  A: 

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
A: 

See http://stackoverflow.com/questions/969130/nslog-tips-and-tricks 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
Cirrostratus