Today, we’re going to create a lightweight logging utility that you can use in any iOS application. This was originally a problem I encountered in an iOS interview a few months ago and I wanted to share my revised solution with you.
Most developers, myself included, rely heavily on
NSLog statements to aid them in their debugging. While this approach certainly has its place, I want to show you the benefits of taking the time to create a proper logging utility.
There are 3 main advantages to this approach.
Firstly, this lightweight implementation allows us to easily log at different severity levels (i.e.
LogLevel). Secondly, we can leverage Swift’s literal expressions so we can add additional context (e.g. filename, function, line number, etc.) to our debug output. Finally, we can use preprocessor macros to ensure we are only logging sensitive information in DEBUG mode.
Here is a simple implementation you can use in your next project:
You’ll notice that it could easily include support for:
- Disabling logging in staging/production.
- Adding additional levels of verbosity/logging levels.
- Logs can be saved to a file or uploaded immediately.
- More granular logging is available than
If you liked this implementation, check out my free iOS eBook: Practical Tips for Junior iOS Developers. If you’re interested in iOS development, please check out my new YouTube channel. Otherwise, check me out on Twitter and I’ll see you next time.