Is it possible to NSLog() without the time and date stamps, and the automatic newline? [duplicate]
Does NSLog() have variants that print without the time and date stamps, and the automatic newline?
Thanks. Now with following code, I can print NSString, cString, or objects:
#import <Foundation/Foundation.h>
#import <stdio.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *s = @"Hello, World!";
NSDate *today = [NSDate date];
NSLog(@"%@", s);
printf("%s at %s", [s UTF8String], [[today description] UTF8String]);
[pool drain];
return 0;
}
Solution 1:
Use printf()
instead of NSLog()
Solution 2:
It bothered me too, so I wrote a function to replace NSLog()
and printf()
:
void IFPrint (NSString *format, ...) {
va_list args;
va_start(args, format);
fputs([[[[NSString alloc] initWithFormat:format arguments:args] autorelease] UTF8String], stdout);
va_end(args);
}
Then, you can just use it instead of NSLog()
(e.g. IFPrint(@"Current date: %@", [NSDate date])
), but it won't print out any timestamps or a newline, and you don't have to mess around with C strings and arrays, and whatnot. It's pretty handy, I'd say.
If you want, check out my full code (I've also written a replacement for fprintf, scanf, and fscanf) here.
(There's also an SO topic about it here).
Solution 3:
This code will work
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(...) {}
#endif
Solution 4:
Define a macro
#if __has_feature(objc_arc)
#define DLog(format, ...) CFShow((__bridge CFStringRef)[NSString stringWithFormat:format, ## __VA_ARGS__]);
#else
#define DLog(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);
#endif
And use this macro in you code like
NSLog(@"Content with time stamp");
DLog(@"Content without time stamp");
Here is the output of console
NSLog->2014-01-28 10:43:17.873 TestApp[452:60b] Content with time stamp
DLog -> Content without time stamp
P.S.
If anyone wants Custom Logs which gives you more info like method name / line number etc. can download the open source MLog.h on GitHub
.
Solution 5:
I like the Itai's solution. I just modified the code to use CFShow under ARC environment.
void CFLog(NSString *format, ...)
{
va_list args;
va_start(args, format);
CFShow((__bridge CFStringRef)[[NSString alloc] initWithFormat:format arguments:args]);
va_end(args);
}