One Simple Trick to Improve Your Firmware Module Logging

Does this sound familiar?

Time to write a new firmware module. Let’s add the initialization, some functions, and pepper in a few printf statements so I can make sure everything is working as expected. Things do not work as expected. Add more code, add more logs. Eventually it works, but now there are logging statements all over the place that are really not needed anymore. So you delete them all. Fast forward some amount of time, and that same module is not working. We blame the hardware, but the only way to know for sure is to add back all of those log statements all over again just to try and figure out what the problem might be.

This has happened to me way more than I would like to admit.

So now when I am developing a new module I start with some macros at the top that help solve this problem. Check out this gist:

As you can see, now I can control whether the module outputs logs with one #define, I can also move this to a preprocessor definition in my IDE or makefile if I need to. Going further, you can add support for different log levels: DEBUG , INFO, ERROR, etc.

Finally, I like that this brings some uniformity to my logs. It forces all logs in this module to be prepended with whatever I want. Now I see logs like this:

[SPI] Initializing interface...

[SPI] Initialization complete.

[BLE] Initializing BLE interface...

[BLE] MAC address is: 11:22:33:44:55:66

[BLE] Advertising started.

[BLE] Initialization complete

This small added clarity in my logs makes it easy to debug and figure out timing - especially when different events start firing off. And if one of those modules is just too noisy - it's a simple one line change to disable just that module's logging.

What tips and tricks do you have to improve your embedded systems logging?

Nick Sinas
Posted
Feb 2, 2022
by
Nick Sinas
Or click here to learn more ->