This is a short blog to record something niche I learned last week about logging in Python. For more information on what logging is, here are a couple of blogs that cover that:
https://www.thedataschool.co.uk/daniel-bostrom/python-logging/
https://medium.com/@sunilnepali844/logging-in-python-made-simple-custom-loggers-multiple-handlers-and-file-output-explained-5e83705a5922
I learned to set up logs for my script and save them to a log file with a basic configuration that look like this:
logging.basicConfig(
filename=log_filename,
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
This works perfectly, but in order to read progress updates in the terminal we had to include both a print and a logger message, which felt a little redundant.

In order to avoid this, you can make a simple change to the basic configuration where you specify handlers. Handlers determine where the log message is sent to and you can have multiple handlers. With the following script, we can define a FileHandler that will print a message to the relevant log file, as well as a StreamHandler that will print a message to the terminal.
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_filename), # to the log file
logging.StreamHandler(), # to the terminal
],
)
Now the print statement is no longer needed:

