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!

4

2 に答える 2

16

これは 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");
于 2010-05-13T00:14:03.683 に答える
4

これはあなたの質問に明示的に答えるものではありませんが、リダイレクトする必要があるのが NSLog の出力だけである場合は、NSLog() の周りにラッパーを使用し、フラグに基づいてファイルに送信するか、通常の NSLog/stderr に送信するかを決定することを検討します。ユーザーが制御できるようにします。

(これを達成するために stderr ストリームを根本的にリダイレクトするというのは、私にとって驚くべき設計のように感じます。また、NSLog レベルより上のラッパーを使用すると、必要に応じて両方の場所に出力を送信することを簡単に選択できます。)

于 2010-01-20T16:58:11.837 に答える