Legends ofPythos
Claim your name
The Standard Library

Logging, timing and statistics

Lesson 5 of 7

Watch the lesson5:45 · with Torsten
print() is fine for quick experiments. In a real program you want more control: messages carry a level, and one setting decides how much detail reaches the screen.

The logging module gives every message a severity tag:
  • DEBUG – development noise
  • INFO – normal milestones (user logged in, order placed)
  • WARNING – something unexpected but handled
  • ERROR – an operation failed
  • CRITICAL – the program cannot continue
logging.basicConfig() sets up the main logger, called root, which every other logger passes its messages up to. Three of its arguments:

level=logging.INFO – messages less serious than INFO (here, DEBUG) are skipped.
format= – the pattern for each line, in the old % style from Formatting output: %(levelname)s puts in the level, %(name)s the logger's name, and %(message)s your message.
stream=sys.stdout – send each line to the output, where print() writes, so this course can read it. sys is a module about Python itself, and sys.stdout is that output.
import logging
import sys

logging.basicConfig(
    level=logging.INFO,
    format='%(levelname)s:%(name)s:%(message)s',
    stream=sys.stdout,
    force=True,
)
logger = logging.getLogger('shop')
# hidden: DEBUG is less serious than INFO
logger.debug('building cart for user 42')
logger.info('order placed: item=book qty=1')
Basic setup and a named logger
Notice the output is one line:
INFO:shop:order placed: item=book qty=1
The DEBUG line never appears. If you later set level=logging.DEBUG, that same logger.debug(...) call prints, and the call itself never changes.

Each level has a method named after it: logger.debug(), logger.info(), logger.warning(), logger.error() and logger.critical().

Quick statistics with statistics

import statistics

data = [2.5, 3.0, 4.5, 6.0]
print(statistics.mean(data))     # average
# the middle value, or halfway between
# the two middle values
print(statistics.median(data))
print(statistics.mode([1, 1, 2]))  # most common
# with no repeats, mode gives the first one
print(statistics.mode([9, 7, 8]))  # 9
print(round(statistics.stdev([2, 4, 6]), 3))
Mean, median, mode and standard deviation

Measuring how long code takes

import time

t0 = time.perf_counter()
for i in range(1_000):
    pass
elapsed = time.perf_counter() - t0
print(f'{elapsed:.6f} seconds')
perf_counter for a single run
In the loop above, 1_000 is just 1000: the _ only makes long numbers easier to read.

timeit.timeit runs a function many times and returns the total time in seconds. It is handy for comparing two ways of doing the same job, without writing your own loop.
import timeit

def square(n):
    return n * n

total = timeit.timeit(lambda: square(12), number=1000)
print(f'{total:.6f} seconds for 1000 calls')
timeit over 1000 calls

Your turn

0 of 3 solved

Exercise 1

+40 XP
Configure logging with logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s', stream=sys.stdout, force=True). Make a logger named 'shop' and store it in a variable called logger. Then log 'building cart' at DEBUG level, 'ready' at INFO level and 'low stock' at WARNING level. Each method is named after its level: logger.debug(...), logger.info(...) and logger.warning(...). Only the last two should appear in the output; print nothing else.
import logging
import sys


# configure logging, get the 'shop' logger, then log the three messages

Run your code to check it against the tests.

Exercise 2

+40 XP
Write measure(func, *args), which calls func(*args), times the call with time.perf_counter() before and after, and returns a tuple of the result and the seconds it took. For example, measure(sum, [1, 2, 3]) returns (6, 0.0000...), where the time is some small float.
import time




def measure(func, *args):
    # perf_counter before and after, return (result, seconds)
    pass

Run your code to check it against the tests.

Exercise 3

+40 XP
Write describe(values), which returns a dictionary with the 'mean', 'median' and 'mode' of a list of numbers, from the statistics module, and the 'stdev' rounded to 2 decimal places. For example, describe([2, 4, 4, 5])['mode'] is 4. When no value repeats, statistics.mode gives the first one.
import statistics




def describe(values):
    pass

Run your code to check it against the tests.