Sunday, July 8, 2012

Write Debug Output to a File

NSLog definitely has its place in debugging. In a previous post I shared a version I wrote that skips displaying the date and object information, you can read more about the debug command I use on a regular basis here.
At some point, capturing debug statements to a file (versus the console) can be helpful to track down bugs. The good news is that you can continue to use NSLog (and/or the debug command from the previous post) by simply making a change to where stderr is directed.

For example, to re-direct stderr to a file “debug.txt” off the root of the system drive, follow these steps:
// Create OS specific path
const char *path = [@"/debug.txt" fileSystemRepresentation];
 
// Specify stderr writes to a file (truncating contents first)
freopen(path, "w", stderr);
Each time you run your application, the contents of the file “debug.txt” will be truncated and all output written to the file. If you would like to keep a running tally of debug output across invocations of the application, you can change ‘freopen’ to append contents as follows:
// Specify stderr appends to a file
freopen(path, "a", stderr);

No comments:

Post a Comment