liveBook · Manning

Logging module

As explained in Python How-To

The logging module is Python's standard-library module for recording application events through loggers, handlers, formatters, and severity levels.

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

How Python How-To covers it

How deep it goes
Works through logger creation, file and stream handlers, severity filtering, and formatting; mentions other handler types without detailing them.
Examples
Uses a task-removal event, a saved log file, console warnings, level-filtered messages, and timestamped records.
What it assumes
Assumes familiarity with Python modules and reading text files while introducing logger creation and configuration.
What you can do after
Operate/configure it to route, filter, and format application records for console viewing and file storage.
How it connects
Connects Logger instances to handlers, LogRecord messages, logging levels, and formatters.

Also explained in

Compare how 4 books explain logging module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.