logging | Python Standard Library – Real Python

The Python logging module provides a framework for generating log messages from Python programs. It’s designed to meet the needs of both simple scripts and complex applications, offering multiple levels of granularity and customization for logging output.

Here’s a quick example:

Key Features

  • Configures logging with different verbosity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  • Supports multiple output destinations, including the terminal and physical files
  • Allows for easy formatting of log messages
  • Facilitates logging across multiple modules
  • Provides a hierarchy of loggers for granular control

Frequently Used Classes and Functions

Examples

Configuring basic logging settings:

Creating and using a named logger:

Common Use Cases

  • Debugging code by tracking program execution
  • Monitoring applications in production environments
  • Recording events for audit or analysis
  • Centralizing logs from multiple modules

Real-World Example

The following script logs a message every time you check whether a file exists:

In this example, you first set up basic logging to show messages at the INFO level or higher with a custom format. In check_file(), check whether the input file exists. In either case, the logging system will display an appropriate message.

Logging in Python

For additional information on related topics, take a look at the following resources: