Redirecting log data on the iPhone


You'd think that NSLog would write to stderr, right? Right? Um, no. At least not on the iPhone. This morning I spent way too much time trying to figure out why my freopen([logPath fileSystemRepresentation], "a", stderr); line wasn't working and redirecting NSLog output to my log file.

Sure, I could *create* the log file with this line but no text was actually going there. That is, until I switched from NSLog to CFShow. Then suddenly everything worked. So if you want to redirect output on the iPhone, you'll need to CFShow unless someone has an idea of what NSLog outputs to. stdapple? stdannoying? Let me know.

Update: Since CFShow doesn't seem to take format strings, I went ahead and wrote up the following log function that seems to work fine with stderr on the iPhone. Let me know if you end up using this and if it's useful:

#include 
void dolog(id formatstring,...)
{
   va_list arglist;
   if (formatstring)
   {
     va_start(arglist, formatstring);
     id outstring = [[NSString alloc] initWithFormat:formatstring arguments:arglist];
     fprintf(stderr, "%s\n", [outstring UTF8String]);
     va_end(arglist);
   }
}
AddThis Social Bookmark Button
Comments (5)

5 Comments

Add [outstring release] before va_end to avoid memory leak.

Sujth said:

Hi ..


I am working with Cooca Touch app for iPhone...

So can u tell me how to create the log file for such an apps??

I mean how to redirect the NSLog to a file and send it later to server.

Dulip said:


hi,

Can i know how to look log.txt file content from my pc. I mean can i get log.txt file on to my PC from iphone.

syberglitch said:

It is better to use macro instead of the whole function for the simple task of logging the string to stderr.

We can use:

#define dolog(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);

syberglitch said:

It is better to use macro instead of the whole function for the simple task of logging the string to stderr.

We can use:


#define dolog(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);

For the author (Erika) of this post I can say check the code before post it as it is not a good think to put something in public which has a memory leak.