8

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!

Ben Clayton
  • 75,781
  • 25
  • 117
  • 124

2 Answers2

16

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
  • 199
  • 1
  • 2
4

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.)

Ben Zotto
  • 67,174
  • 23
  • 136
  • 201
  • Second that! Do not redirect the stderr indiscriminately! – Adam Woś Jan 20 '10 at 17:03
  • 1
    There are valid reasons for redirecting all NSLog calls to a file, for example if you need to capture logs generated by third party libraries which use NSLog internally. – irodrigo17 Jun 26 '15 at 18:06