logging

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:

Python
>>> import logging
>>> logging.warning("This is a warning message")
WARNING:root:This is a warning message

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

Object Type Description
logging.basicConfig() Function Configures basic logging settings
logging.getLogger() Function Retrieves or creates a named logger
logging.Logger Class Represents a named logging channel
logging.Handler Class Provides a base class for all handlers that send log messages to their final destination
logging.Formatter Class Formats log messages

Examples

Configuring basic logging settings:

Python
>>> import logging

>>> logging.basicConfig(level=logging.INFO)
>>> logging.info("This is an info message")
INFO:root:This is an info message

Creating and using a named logger:

Python
>>> logger = logging.getLogger("custom_logger")
>>> logger.warning("This is a warning from custom_logger")
WARNING:custom_logger:This is a warning from custom_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:

Python
>>> from pathlib import Path
>>> import logging

>>> logging.basicConfig(
...     level=logging.INFO,
...     format='%(levelname)s: %(message)s'
... )

>>> def check_file(filename):
...     file_path = Path(filename)
...     logging.info(f"Checking if file '{file_path}' exists...")
...
...     if file_path.exists():
...         logging.info(f"File found: {file_path}")
...         return True
...     else:
...         logging.warning(f"File not found: {file_path}")
...         return False
...

>>> check_file("data.txt")
WARNING:root:File not found: data.txt
False
>>> check_file("notes.md")
WARNING:root:File not found: notes.md
False

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.

Tutorial

Logging in Python

If you use Python's print() function to get information about the flow of your programs, then logging is the natural next step for you. This tutorial will guide you through creating your first logs and show you ways to curate them to grow with your projects.

intermediate best-practices tools

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


By Leodanis Pozo Ramos • Updated July 14, 2025