27. Logging
The logging module is the standard-library way to record what a program is doing. It is better than scattering print() calls through larger programs because it has levels, formatting, and better control.
27.1. Basic logging
Set up a basic logger and emit messages at several levels.
1import logging
2
3logging.basicConfig(level=logging.INFO)
4
5logging.debug('debug details')
6logging.info('application started')
7logging.warning('low disk space')
8logging.error('something went wrong')
27.2. Logging to a file
You can write log output to a file instead of the console.
1import logging
2
3logging.basicConfig(
4 filename='app.log',
5 level=logging.INFO,
6 format='%(levelname)s:%(message)s',
7)
8
9logging.info('file logger ready')
10logging.warning('watch this condition')
27.3. Why logging matters
Logging is especially helpful when a script grows into a real application. It tells you what happened, when it happened, and where something failed.
27.4. Exercise
Create a script that processes a list of usernames. Log an INFO message for each valid username and a WARNING message for any empty username.
27.4.1. Solution
1import logging
2
3logging.basicConfig(level=logging.INFO)
4
5for username in ['ava', '', 'mia']:
6 if not username:
7 logging.warning('empty username encountered')
8 else:
9 logging.info('processing %s', username)