Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: Once I have redirected NSLog to a file, how do I revert it to the console?

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!

like image 490
Ben Clayton Avatar asked Jan 20 '10 16:01

Ben Clayton


1 Answers

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");
like image 107
G Mauri Avatar answered Sep 23 '22 16:09

G Mauri