Python Standard Library logging module

Python 3.x Standard Library (introduced in Python 2.3) · active · verified Mon Apr 13

The `logging` module is a robust and flexible event logging system for Python applications and libraries, integrated into the Python Standard Library since version 2.3. It enables all Python modules to participate in logging, facilitating the integration of messages from applications and third-party modules into a unified log. The module provides extensive functionality to produce structured log messages and direct them to various destinations such as the console, files, or network sockets.

Warnings

Imports

Quickstart

This quickstart demonstrates both basic `basicConfig` usage for simple scripts and a more robust application-level setup using a named logger with a `FileHandler` and custom formatter. It also shows how to prevent propagation to avoid duplicate messages.

import logging
import os

# Basic configuration for quick scripts (logs to console, INFO level and above)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Recommended for applications: get a named logger
logger = logging.getLogger(__name__)

# Configure a file handler for a more complex setup
log_file_path = os.environ.get('LOG_FILE', 'application.log')
file_handler = logging.FileHandler(log_file_path)
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

# Prevent messages from propagating to the root logger handlers (often console) if file is primary
logger.propagate = False

# Example log messages
logger.debug('This is a debug message - will only go to file handler.')
logger.info('This is an info message.')
logger.warning('This is a warning message!')
logger.error('This is an error message!')
logger.critical('This is a critical message!', exc_info=True)

print(f"\nCheck '{log_file_path}' for detailed logs.")

view raw JSON →