Logging

Learn about the importance of logging debug, informational, and error messages.

An introduction to logging

Logging is the means by which we keep track of events that occur during the execution of a program. Whether we realize it or not, we’ve all done logging in our programs in one way or another. We all know about the Python print statement. Every Python programmer starts off debugging by writing print statements throughout their code to print informational and error messages and display variable values. Let’s take a look at an example.

Press + to interact
import sys
def sum_list(a):
print("Computing sum...")
if a == []:
print("ERROR: List is empty.", file=sys.stderr)
raise Exception("List is empty")
sum_ = sum(a)
print("Sum computing done.")
return sum_
if __name__ == "__main__":
try:
sum_ = sum_list([1, 2, 3, 4, 5])
print(sum_)
sum_ = sum_list([])
print(sum_)
except:
print("ERROR: Sum computing failed.", file=sys.stderr)

In this code, we have a function that computes the sum of all elements in a list. There are a couple of informational messages, Computing sum... and Sum computing done. in lines 5 and ...