Via my feeds yesterday, I spotted a post entitled Say Goodbye to Print Statements: How to Use Logger for Effective Debugging which suggests using the Python logging
package rather than print
statements for casual debugging.
Hmmm…
So I wondered whether this might be a handy thing to suggest to students.
It’s a little bit of faff to set up a logger, but if we want students to use this sort of thing we need to minimise the boilerplate, and try to resist the temptation to pre-load packages into the student Python environment*.
* The reason being we want students to be able to do things elsewhere, and if we load too much stuff behind the scenes, if they move to a new environment, they may wonder why things don’t work the same was as they seemed to work before.
Repo for the package I cobbled together here: https://github.com/innovationOUtside/ou-logger-py
One good reason for using a logger is that you can set a logging level, and then include logging (“print”) statements that only produce an output at or above that logging level:
logger.setLevel(LEVEL)
# LEVEL: DEBUG, INFO, WARNING, ERROR, CRITICAL
logger.error('This is an error message')
logger.warning('This is a warning message')
Thinks: it would be nice to have logging groups as well, so maybe something like:
logger.setGroups(["ingest", "analysis"]
logger.error('This is an ingest error message', "ingest")
I guess the way to do that is just to have different loggers (logger1
, logger2
, etc)? Related issue here.
Anyway. Basic student use…
STEP 1. A simple package that lets you just get going.
from ou_logger import logger
But then I wondered… how about if the logger can also speak the message aloud? We’re working in Jupyter notebooks, so we can get access to the browser text-to-speech module
So, STEP 2:
# Via ChatGPT
from IPython.display import display, Javascript
# Define a custom logging handler that speaks the log messages using browser TTS
class BrowserTTSHandler(logging.Handler):
def emit(self, record):
msg = self.format(record)
# Use JavaScript to speak the message in the browser
display(
Javascript(f'speechSynthesis.speak(new SpeechSynthesisUtterance("{msg}"))')
)
So now with a from ou_logger import logger, set_handler
we can say:
set_handler("text")
set_handler("text, tts")
set_handler("tts")
If we have the "tts"
handler set, the message will be spoken aloud by the browser speechSynthesis
module.
When I tested this, the JupyterLab environment I was using also had my jupyterlab_cell_status_extension
installed with the audible cell completion alert and error message TTS enabled which made for quite an audible experience…