The point of logging.

I find it good practice to have code report informational updates while running to let me know things are working as expected. Assertions and tests are nice for problems that are foreseeable, but I often catch surprising problems by noticing something funny in the output as a code is running.

During development, I usually have very detailed reporting, which gets tedious to read after the code is working. When I used to delete or comment the print statements out, I may realize something needs to be fixed or upgraded, and I needed those statements back. Putting the statements back/uncommenting them is tedious and I often forget where it is important to do reporting.

Logging is a way to control the level of reporting as well as where the reports are sent (STDOUT or maybe to a file?) in a central location in your code. For example, setting level to DEBUG will print detailed reports, but setting it to WARNING will silence everything which isn’t reporting bad news. The main module I’ll use is logging.

Simple usage.

The tutorial is the best introduction to this tool, but here’s some highlights.

import logging
from numpy.random import random 

test = random(100,100)

logging.debug("Random matrix generated:")
logging.debug(test)

logging.info(f"Random matrix mean: {test.mean()}")

if test.shape[0] > 1e4:
  logging.warn("This matrix is probably too large!")

To set the level of output, use

# Set the output level to "debug".
logging.basicConfig(level=logging.DEBUG)

for example. The default level is WARNING, which only reports when something is going wrong.