Python Logging Module: Basics and Best Practices πŸ“

Log file icon

Python Logging Module: Basics and Best Practices πŸ“

The logging module is essential for tracking application behavior and diagnosing issues. Let’s explore how to configure it step by step.

1. Basic Configuration

import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s [%(levelname)s] %(message)s')

logging.debug("Debug message (usually not shown)")
logging.info("Application has started")
logging.warning("Warning: High usage detected")
logging.error("An error occurred!")
logging.critical("Critical failure!")

2. Adding File and Stream Handlers

import logging

logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)

# Stream handler (console)
console_h = logging.StreamHandler()
console_h.setLevel(logging.INFO)

# File handler
file_h = logging.FileHandler("app.log", encoding="utf-8")
file_h.setLevel(logging.DEBUG)

# Formatter
fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
console_h.setFormatter(fmt)
file_h.setFormatter(fmt)

logger.addHandler(console_h)
logger.addHandler(file_h)

logger.info("This goes to both console and file")
logger.debug("Debug level logged only to file")

For core function tutorials, see Understanding Python Functions.

Summary

  • Use basicConfig for quick setup of log levels and formatting.
  • Add multiple handlers to direct logs to console, files, or elsewhere.
  • Customize message layouts with Formatter.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More