Redirecting 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

Jonathan Wight
2008 12 11

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

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

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

2008 12 12

Or try man 3 freopen.

2012 07 09

I have used tail -f /NSLog.txt command in terminal, which made my XCode console doesn't show any log. I want to roll back and make my console work properly as earlier.

Can any one tell us command to roll back this.

Follow me on Twitter
Planet Cocoa

2011 02 22Distance field
2010 07 202Binding through NSApp
2010 05 122Forwarding invocations
2010 02 272Core Image black fringes
2010 02 21Quickest Way to Shell
2010 02 08Who's calling ?
2009 09 2138 ways to use Blocks in Snow Leopard
2009 08 182Bracket Mess
2009 08 124Taming JavascriptCore within and without WebView
2009 04 15Debugging with Activity Monitor
2009 03 25How Core Image Color Tracking works
2009 03 1510Custom NSThemeFrame
2009 03 10Which framework is running ?
2009 03 074CoreUI can paint pretty big
2009 02 18Localization with functions
2009 01 30Did you forget to nest alloc and init?
2009 01 16JSCocoa on the iPhone
2009 01 11Mixing WebView and JavascriptCore
2009 01 09Badge overflow
2009 01 09Find your Garbage Collection leaks with Instruments

Powered by MediaWiki