Need to keep a record of application events after the console closes? Python’s standard-library logging module sends messages through a Logger to one or more handlers. A FileHandler preserves records in a file; a StreamHandler displays them in the console. Unlike print output alone, a log file can be examined later. section 12.1.1 section 12.1.2 section 12.1.3
Record and format an application event
import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)s] - %(name)s - %(message)s" )) logger.addHandler(handler) logger.warning("Could not save the task") The console record includes a timestamp, WARNING, the module name, and the message. To preserve it instead, attach a logging.FileHandler("taskier.log"); both handlers can be attached when you want immediate feedback and a saved record. section 12.1.1 section 12.1.2 section 12.1.3 section 12.2.3
Configure the logger for the records you need:
- Use logging.getLogger(__name__) rather than constructing Logger directly. Repeated calls for the same name return the same logger, so its configuration can be shared. section 12.1.1
- Choose a severity: DEBUG, INFO, WARNING, ERROR, or CRITICAL, in increasing order. A logger set to WARNING captures warnings and more severe records, but not INFO or DEBUG records. section 12.2.1
- Set a formatter on a handler when timestamps, severity, and module names will help locate a problem. Formatter patterns use %-style fields rather than f-strings. section 12.2.3



