Logging to your own file using NSLog

Have you ever found yourself needing to have your application record quite a bit of data? Think pushing it to the user’s console is messy? (it is!) Here’s your answer. In the main.m of your cocoa application, simply add the following imports:

Source

#import <stdio.h.
#import <sys/param.h>

Then make your “main” method look like this:

int main(int argc, char *argv[]) {
  id pool = [NSAutoreleasePool new];

  NSString *applicationName = [NSString stringWithFormat: @"Library/Logs/%@.log", [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleName"]]; 
  NSString *logPath = [NSHomeDirectory() stringByAppendingPathComponent: applicationName];
        freopen([logPath fileSystemRepresentation], "a", stderr);

  [pool release];

  return NSApplicationMain(argc,  (const char **) argv);
 }

Now, all of your logging messages will be pushed to a log file with the same name as your application under ~/Library/Logs/. Oh, and because ZNLog uses NSLog to do it’s work, you can use this with my own, kickass logging implementation as well.

Comments

Gravatar for Andrew James.

Great code snip­pet, just what i was look­ing for. I won­der if it would work in Apple­Script projects as well…

Posted by Andrew James on

Sorry, this conversation has finished.

This post is a bit old now, so I've closed the conversation. If you're keen to keep talking about it, please email me directly.