2008 12 11Redirecting NSLog to a file
NSLogConsole will do that for you and more. Here's the simpler version :
- (BOOL)redirectNSLog { // Create log file [@"" writeToFile:@"/NSLog.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil]; id fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/NSLog.txt"]; if (!fileHandle) return NSLog(@"Opening log failed"), NO; [fileHandle retain]; // Redirect stderr int err = dup2([fileHandle fileDescriptor], STDERR_FILENO); if (!err) return NSLog(@"Couldn't redirect stderr"), NO; return YES; }
This will redirect to a root file /NSLog.txt
. After that, launch your app and use tail in Terminal to see your log updates :
> tail -f /NSLog.txt 2008-12-11 21:02:51.967 YourApp[39541:20b] Hello from NSLog 2008-12-11 21:02:52.694 YourApp[39541:20b] Hello from NSLog, again 2008-12-11 21:02:58.127 YourApp[39541:20b] Hello from NSLog, and again
Patrick Geiller
2008 12 11
Thanks for the link ! As dup2 does redirect all stderr, it's really quite blunt.
I like that NSLog
prints both in Xcode and in the console — opening Console. app is a quick and easy way to see if/where your app failed, so I'm all in favor of NSLog
, debug or release :)
That doesn't strike me as the best way. All stderr output will go to the file in that case. That might not be optimal.
I used the following code to enable NSLog on the early iPhone betas (when NSLog was broken):
http://code.google.com/p/touchcode/source/browse/trunk/Experimental/Deprecated/TouchDebugging.m
(Not sure who I got the original code from - Jens maybe?)
It's my opinion that NSLog shouldn't exist in a non-debug app - you should be logging via a different mechanism (asl springs to mind). But these techniques are good as work arounds.