NSLog: Logging Tips

Sometimes it’s way better to just use a simple log then debugging your app step by step. That’s when NSLog comes in handy.
There’s a lot of ways to use NSLog in your code, I’ll show some of my favorites.
int myInt = 1;
float myFloat = 2.3;
NSString *myString = @”Hello Log”;
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
NSLog(@”Int [%i]”, myInt);
NSLog(@”Float [%f]”, myFloat);
NSLog(@”String [%@]”, myString);
NSLog(@”Object [%@]”, myView);
This is how the log will look like:
Int [1]
Float [2.300000]
String [Hello Log]
Object [<UIView: 0x5c07950; frame = (0 0; 20 40); layer = <CALayer: 0x5c07920>>]
What I’m doing there is, logging an Int, Float, NSString and an UIView. As you can see I always add some brackets in the log, and why do I do this? That’s only to know exactly what’s being logged. Imagine that I have a NSString with some white spaces, I will not know that it has the white spaces unless I add the brackets. Here’s an example :
NSString *test = @”Test   “;
NSLog(@”log: %@”, test);
Result : log: Test

NSString *test = @”Test   “;
NSLog(@”log: [%@]”, test);
Result : log: [Test   ]

Logging CGGeometry

Now, let’s say that you want to log some CGRect, CGPoint or CGSize, just transform them into NSString with :

Log Macro

Here’s a cool tip, although I’m not a macro fan, there’s one that’ great for logging:
#define MYLOG(fmt, …) NSLog((@”File [%s] Method [%s] Line [%d]: ” fmt),__FILE__, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
and you can use exactly like an NSLog, like so :
MYLOG(@”Hello Log”);
What this will do is:
  • __FILE__ : file path and name.
  • __PRETTY_FUNCTION__ : name of the method.
  • __LINE__ : the line of the method
You can edit this macro as you please, remove or reorder the parameters. That’s how the output will look like :
File [/Users/user/Desktop/Log/Classes/LogAppDelegate.m] Method [-[LogAppDelegate application:didFinishLaunchingWithOptions:]] Line [25]: Hello Log
That’s some simple tips that I have to share about the NSLog, if anyone has anything else to add, please share it in the comments.
That’s it, thanks for all the fishes 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s