Controlling output using Adafruit Logger in CircuitPython
Print statements are the standard debugging and tracing tool for programs running on microcontrollers in non-real-time sections of code. Print statements are a great tool to generate basic output as long as you always want the output and always want the output to go to a serial port.
Use the logger if you want to be able to turn print statements on and off without having to continually re-comment and de-comment them.
The Adafruit logging library lets you throttle your log output reducing the amount generated. It lets categorize your logging criticality with levels like DEBUG, INFO, WARN, ERROR, etc. The logger then lets you set the minimum level of criticality for messages to actually be emitted. If you set your filter level at WARN then no DEBUG or INFO messages show up in the logs/console. This can speed up an application and reduce resource usage while retaining the ability to enable more information if you need it.
The logging library also lets you treat that log output as a datastream that can be sent somewhere else like an SD card or an alternate UART.
This chart shows how logging is used in the sample program referenced below.References
- Learn about Adafruit logger https://learn.adafruit.com/a-logger-for-circuitpython/using-a-logger
- Read the logger docs https://docs.circuitpython.org/projects/logging/en/latest/api.html
- Read code that uses the logger and lets you change the amount of output via serial port commands https://github.com/freemansoft/Adafruit-Trinkey-CircuitPython/blob/main/Indicator-Light-neopixel/main.py
- Joe's YouTube Video
Installing Logging
Configuring Logging
You must import the logging library and initialize it. The library supports multiple independently configure loggers in case you want different levels or different logging targets in your program. I only needed one logger with all the output going to the USB serial port.Here I injected the logger it into main() that then logged messages using logger.info() logger.debug() and logger.error(). The logger has been configured at the INFO level.
- logger.info() and logger.error() messages appear while logger.debug() are filtered out.
- logger.debug() message in the text will appear if we change the logging filter level to logging.DEBUG
Sample Output
- The request for help resulted in print() driven output.
- There is no debug() output.
- We see an error() message when bad input was provided
- The request for help resulted in print() driven output.
- We see an error() message when bad input was provided
- The logging level is changed on the fly to DEBUG
- DEBUG level messages appear for accepting the input and for state changes
Comments
Post a Comment