Using Objective-C Macros to Conditionally Log
During the course of developing and debugging my first iOS apps I’ve realized that there has to be at least a semi-decent way of using log statements for debugging messages as well as error messages without a lot of code overhead and manual changes when switching between building for Release and Debug.
Using macros and compiler settings, you too can quickly separate the statements out and streamline your debugging/logging code.
Creating Your Macros
Find the -Prefix.pch header file for your project and open it for editing. If your project’s name is MyProject you will look for MyProject-Prefix.pch.
Add the following lines to the end of your Prefix header file:
// Macro wrapper for NSLog only if debug mode has been enabled
#define AshDebugLog(fmt,...) NSLog(@"%@",[NSString stringWithFormat:(fmt), ##__VA_ARGS__]);
// If debug mode hasn't been enabled, don't do anything when the macro is called
// Log using the same parameters above but include the function name and source code line number in the log statement
#define AshDebugLogDetailed(fmt, ...) NSLog((@"Func: %s, Line: %d, " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
// This macro will create a detailed log message and run even during a production build
#define AshDetailedLog(fmt, ...) NSLog((@"Func: %s, Line: %d, " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
What We Did
I have prefixed each macro with Ash so that there is no confusing them as macros I created. As you can also see, we have created a few different ways to log. We have a standard wrapper for NSLog that we will call instead of NSLog that will only fire if we’ve built using a debug mode flag. We also have two different methods for creating detailed log messages on the fly that will include our log message along with the function and line number the message originates from. The nice thing about these macros is that you can easily change the string format to log in any way that you want.
Select your project in the Xcode explorer/left pane
- Select Build Settings in the Xcode center window
Search for preprocessor in the Build Settings section and add DEBUGGING as a Debug Preprocessor Macro.