开发者

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

开发者 https://www.devze.com 2022-12-17 19:20 出处:网络
I\'m using: #if TARGET_IPHONE_SIMULATOR == 0 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

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:NSASCIIStrin开发者_Go百科gEncoding],"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!


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");


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

0

精彩评论

暂无评论...
验证码 换一张
取 消