views:

499

answers:

2

I'm using:

#if TARGET_IPHONE_SIMULATOR == 0
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"];
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
#endif

.. to redirect NSLog to a file, which works great incidentally.

I want to make logging to file something the user of my app can turn on and off.. so does anyone know how I go about redirecting NSLog/stderr back to the console?

Thanks!

+2  A: 

This doesn't explicitly answer your question, but if all you need to redirect is NSLog's output, then I would consider using a wrapper around NSLog() and deciding there whether to send to file or to regular NSLog/stderr based on a flag that you keep around that the user can control.

(It feels like a surprising design to me to fundamentally redirect the stderr stream to accomplish this-- and with a wrapper above the NSLog level, you could just as easily choose to send the output to both places if you ever wanted.)

quixoto
Second that! Do not redirect the stderr indiscriminately!
Adam Woś
ok got it. Thanks guys.
Ben Clayton
+1  A: 

This is taken from http://www.atomicbird.com/blog/2007/07/code-quickie-redirect-nslog

// Save stderr so it can be restored.
int stderrSave = dup(STDERR_FILENO);

// Send stderr to our file
FILE *newStderr = freopen("/tmp/redirect.log", "a", stderr);

NSLog(@"This goes to the file");

// Flush before restoring stderr
fflush(stderr);

// Now restore stderr, so new output goes to console.
dup2(stderrSave, STDERR_FILENO);
close(stderrSave);

// This NSLog will go to the console.
NSLog(@"This goes to the console");
G Mauri