Override NSLOG in prefix.pch iOS

I read this article: http://weakreference.wordpress.com/2011/06/22/overriding-nslog-on-ios/ .

The idea of โ€‹โ€‹the article is to add these two things to the prefix.pch file of your application so that you can override the behavior of NSLog.

Two things I add:

#define NSLog(...) customLogger(__VA_ARGS__); 

and

 void customLogger(NSString *format, ...) { va_list argumentList; va_start(argumentList, format); NSMutableString * message = [[NSMutableString alloc] initWithFormat:format arguments:argumentList]; [message appendString:@"Our Logger!"]; // Our custom Message! NSLogv(message, argumentList); // Originally NSLog is a wrapper around NSLogv. va_end(argumentList); [message release]; } 

xCode throws an o error matching error, which finds duplicates of customLogger.

Has anyone successfully redefined NSLog?

Thanks!

Edit in response to Rob:

Good Excellent. We are making progress! I moved things the same way you asked. Here is what we have now:

My user log:

 void customLogger(NSString *format, ...) { va_list args; va_start(args, format); va_end(args); [newLogger log:format withArgs:args]; } //This is a newLogger Method + (void) log:(NSString *)format withArgs:(va_list) args{ NSArray *occ = [format componentsSeparatedByString:@"%@"]; NSInteger characterCount = [occ count]; NSArray *stringItems = [format componentsSeparatedByString:@"%@"]; NSMutableString *tmp = [[NSMutableString alloc] initWithFormat: @"%@",[stringItems objectAtIndex:0]]; for( int i = 1; i < characterCount; i++ ) { NSString *value = va_arg(args, NSString *); [tmp appendString:value]; [tmp appendString:[stringItems objectAtIndex:i]]; } // Need to alter the above and actually do something with the args! [tmp appendString:@"\n"]; [[newLogger sharedInstance].logBuffer appendString:tmp]; if ([newLogger sharedInstance].textTarget){ [[newLogger sharedInstance].textTarget setText:sharedInstance.logBuffer]; } } 

When I call + log, I get a SIBABRT error in Thread 1.

+4
source share
2 answers

It looks like you defined customLogger in your .pch file. This means that every .m file includes it, so every .o file created by your project contains its own copy of customLogger . This is why you get duplicate character errors from the linker.

You just need to declare .pch in .pch , for example:

 void customLogger(NSString *format, ...); 

And create a customLogger.m file containing the definition.

+5
source

Try this code. It cancels the NSLog. Write the code below in the ClassName-Prefix.pch file at the end

 #ifdef DEBUG # define DLog(...) NSLog(__VA_ARGS__) #else # define DLog(...) /* */ #endif 

and in the file ViewController.m,

 - (void)viewDidLoad { [super viewDidLoad]; DLog(@"printing from DLog"); DLog(@"printing again from DLog"); // Do any additional setup after loading the view, typically from a nib. } 

This will print the sentence in the console. Let me know if you find difficulties.

-1
source

All Articles