views:

627

answers:

2

I want to be able to write the contents of NSLog to a file I specify, or I need a function that writes a log to a file, for example:

WriteLog(@"some activity by the user");
WriteLog(@"some more activity by the user");

but I want the output to look like this:

12-25-2009 1:30:00PM some activity by the user
12-25-2009 1:35:00PM some more activity by the user

does anyone know how I can do this? Note that I need the date and time at the beginning of the line.

ALSO: for some reason, freopen WILL NOT write any data to the file, it will create the file, just no output!

A: 

Well NSLog doesn't really let you customize where its output goes, so you are best off rolling your own logging functions. Personally I would go with the log_fine, log_info style and use something like NSString's writeToFile method:

[log_string writeToFile:@"log.log" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

Only problem is using the atomic option could affect the performance, so this may be a better solution:

NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:"log.log"];
[output seekToEndOfFile];
[output writeData:[log_string dataUsingEncoding:NSUTF8StringEncoding]];

As for formatting the date/time, see the NSDateFormatter class.

Mike Weller
A: 

I wrote my own log to file class but I discovered that in the vast majority of cases it was easier to just copy the contents of the debugger console,paste it to a file and use editing or scripts to process it if necessary. That works well even for very large dumps. I've even dumped tables that way. It's inelegant but way, way quicker and less error prone than futzing with files.

TechZen
I actually figured out a really nice way to write to my logs by creating my own function! Thanks for the suggestion!
AWright4911