Alex Rivera | Logout

Is it possible to NSLog() without the time and date stamps, and the automatic newline?

Asked 2010-08-15T11:48:08.003
27

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;
}  
Edit
Report

2 Answers

4

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);
}
answered 2012-12-14T14:05:04.717
3

the FIRST thing I do on ANY project is drop in (my condensed version of) this class... which gets rid of ALL the NONSENSE in NSLog… Place this at the top of an .m file - and your console output will be PERFECT.

#import <Foundation/Foundation.h>
#import <stdio.h>
#define MLogString(s,...) \
    [MLog logFile:__FILE__ lineNumber:__LINE__ \
        format:(s),##__VA_ARGS__]
@interface MLog : NSObject { }
+ (void) logFile:  (char*) sourceFile lineNumber: (int) lineNumber format: (NSString*) format, ...;
+ (void) setLogOn: (BOOL)  logOn;
@end
#ifndef NDEBUG
extern void _NSSetLogCStringFunction(void (*)(const char *string, unsigned length, BOOL withSyslogBanner));
static void PrintNSLogMessage(const char *string, unsigned length, BOOL withSyslogBanner){ puts(string); }
static void HackNSLog(void) __attribute__((constructor));
static void HackNSLog(void){ _NSSetLogCStringFunction(PrintNSLogMessage); }
#endif
static BOOL __MLogOn = NO;
@implementation MLog
+ (void) initialize { char * env = getenv("MLogOn");
     if (strcmp(env == NULL ? "" : env, "NO") != 0) __MLogOn = YES;
}
+ (void) logFile: (char *) sourceFile lineNumber: (int) lineNumber format: (NSString *) format, ...; {
    va_list ap;    NSString *print, *file;
    if (__MLogOn == NO) return;   va_start(ap, format);
    file  = [[NSString alloc] initWithBytes: sourceFile                  length:strlen(sourceFile) encoding: NSUTF8StringEncoding];
    print = [[NSString alloc] initWithFormat:format arguments: ap];
    va_end(ap); // NSLog handles synchronization issues
    NSLog(@"%s: %d %@", [[file lastPathComponent] UTF8String], lineNumber, print); return;
}
+ (void) setLogOn: (BOOL) logOn { __MLogOn = logOn; }
@end
answered 2012-02-29T15:25:23.810

Your Answer