Wednesday, 30 October 2013

Trick: NSLog without date time stamp, application name, and process id info.

In my previous post, I have discussed that how to create a custom log But today I am going to discuss a new trick that how to hide  date time stamp, application name, and process id info, when you are going to print your information through NSLogs.

The NSLogs original output is 

2013-10-28 14:58:04.816 MyProject[17368:70b] Hi my new Message

But you can modify it to more simple way:

(-[Sample viewDidLoad]) (Sample.m:33) Hi my new Message

Isn't it a cool wat to show your logs without any timeStamp, No process ID. You can also implement this as it is very simple. Just follow the steps below:

Step 1: Create a Constant.h file in your project. First Right click on your project name

NoteIf you already have a Constants.h file or any other file in which you are storing your constants then skip this step and just write the below code there, else follow the step 2

then Select C/C++ under iOS section and Select a header file.

Then Name it as Constants.h and Add this file to your project.

Step 2: Now open the Constants.h file and write the following code there: 

 #define NSLog(args...) CustomLog(__FILE__, __LINE__, __PRETTY_FUNCTION__, args)  
 static inline void CustomLog(const char *file, int lineNumber, const char *functionName, NSString *format, ...)  
   // Type to hold information about variable arguments.  
   va_list ap;  
   // Initialize a variable argument list.  
   va_start (ap, format);  
   // NSLog only adds a newline to the end of the NSLog format if  
   // one is not already there.  
   // Here we are utilizing this feature of NSLog()  
   if (![format hasSuffix: @"\n"])  
     format = [format stringByAppendingString: @"\n"];  
   NSString *body = [[NSString alloc] initWithFormat:format arguments:ap];  
   // End using variable argument list.  
   va_end (ap);  
   NSString *fileName = [[NSString stringWithUTF8String:file] lastPathComponent];  
   fprintf(stderr, "(%s) (%s:%d) %s",  
       functionName, [fileName UTF8String],  
       lineNumber, [body UTF8String]);  

Step 3 : After adding this code in Constants.h file, open the Prefix.pch file in your project . You can find it in Supporting Files group in Project navigator.

 #ifdef __OBJC__  
   #import <UIKit/UIKit.h>  
   #import <Foundation/Foundation.h>  
   #import "Constants.h"  

By adding this file here you do not have need to import this file in every file.

All set now. What you have to do is to implement the new NSLog method and there it is your new logs without timestamps and processIds..!!

Share if you find it worthful.. enjoy coding..!!!

1 comment:

  1. Absolutely fantastic posting! Lots of useful information and inspiration, both of which we all need!Relay appreciate your work.
    iPhone app development perth