Skip to main content

Command Palette

Search for a command to run...

Logging in Python: A Comprehensive Guide

Updated
โ€ข2 min read
Logging in Python: A Comprehensive Guide
N

I am a Tech Enthusiast having 13+ years of experience in ๐ˆ๐“ as a ๐‚๐จ๐ง๐ฌ๐ฎ๐ฅ๐ญ๐š๐ง๐ญ, ๐‚๐จ๐ซ๐ฉ๐จ๐ซ๐š๐ญ๐ž ๐“๐ซ๐š๐ข๐ง๐ž๐ซ, ๐Œ๐ž๐ง๐ญ๐จ๐ซ, with 12+ years in training and mentoring in ๐’๐จ๐Ÿ๐ญ๐ฐ๐š๐ซ๐ž ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐ƒ๐š๐ญ๐š ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐“๐ž๐ฌ๐ญ ๐€๐ฎ๐ญ๐จ๐ฆ๐š๐ญ๐ข๐จ๐ง ๐š๐ง๐ ๐ƒ๐š๐ญ๐š ๐’๐œ๐ข๐ž๐ง๐œ๐ž. I have ๐’•๐’“๐’‚๐’Š๐’๐’†๐’… ๐’Ž๐’๐’“๐’† ๐’•๐’‰๐’‚๐’ 10,000+ ๐‘ฐ๐‘ป ๐‘ท๐’“๐’๐’‡๐’†๐’”๐’”๐’Š๐’๐’๐’‚๐’๐’” and ๐’„๐’๐’๐’…๐’–๐’„๐’•๐’†๐’… ๐’Ž๐’๐’“๐’† ๐’•๐’‰๐’‚๐’ 500+ ๐’•๐’“๐’‚๐’Š๐’๐’Š๐’๐’ˆ ๐’”๐’†๐’”๐’”๐’Š๐’๐’๐’” in the areas of ๐’๐จ๐Ÿ๐ญ๐ฐ๐š๐ซ๐ž ๐ƒ๐ž๐ฏ๐ž๐ฅ๐จ๐ฉ๐ฆ๐ž๐ง๐ญ, ๐ƒ๐š๐ญ๐š ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐‚๐ฅ๐จ๐ฎ๐, ๐ƒ๐š๐ญ๐š ๐€๐ง๐š๐ฅ๐ฒ๐ฌ๐ข๐ฌ, ๐ƒ๐š๐ญ๐š ๐•๐ข๐ฌ๐ฎ๐š๐ฅ๐ข๐ณ๐š๐ญ๐ข๐จ๐ง๐ฌ, ๐€๐ซ๐ญ๐ข๐Ÿ๐ข๐œ๐ข๐š๐ฅ ๐ˆ๐ง๐ญ๐ž๐ฅ๐ฅ๐ข๐ ๐ž๐ง๐œ๐ž ๐š๐ง๐ ๐Œ๐š๐œ๐ก๐ข๐ง๐ž ๐‹๐ž๐š๐ซ๐ง๐ข๐ง๐ . I am interested in ๐ฐ๐ซ๐ข๐ญ๐ข๐ง๐  ๐›๐ฅ๐จ๐ ๐ฌ, ๐ฌ๐ก๐š๐ซ๐ข๐ง๐  ๐ญ๐ž๐œ๐ก๐ง๐ข๐œ๐š๐ฅ ๐ค๐ง๐จ๐ฐ๐ฅ๐ž๐๐ ๐ž, ๐ฌ๐จ๐ฅ๐ฏ๐ข๐ง๐  ๐ญ๐ž๐œ๐ก๐ง๐ข๐œ๐š๐ฅ ๐ข๐ฌ๐ฌ๐ฎ๐ž๐ฌ, ๐ซ๐ž๐š๐๐ข๐ง๐  ๐š๐ง๐ ๐ฅ๐ž๐š๐ซ๐ง๐ข๐ง๐  new subjects.

Introduction to Logging

Logging is a crucial aspect of software development that helps developers track events, debug issues, and monitor application behavior. Instead of using print() statements for debugging, Python's logging module provides a structured, efficient, and flexible way to record messages.

Why Use Logging Instead of print()?

  1. Severity Levels: Logs allow categorizing messages into different levels (INFO, WARNING, ERROR, etc.).

  2. Better Debugging: Logs persist even after execution, unlike print(), which disappears.

  3. Custom Formatting: Logging provides timestamps, log levels, and message customization.

  4. Multiple Output Streams: Logs can be stored in files, databases, or external monitoring services.

Basic Logging in Python

Python provides a built-in logging module that allows different log levels:

1. Importing the logging Module

import logging

2. Setting Up Basic Logging Configuration

logging.basicConfig(level=logging.INFO)  # Set log level to INFO
logging.info("This is an INFO message")  # Output: INFO:root:This is an INFO message

3. Logging Different Levels

Python defines multiple logging levels:

logging.debug("Debugging details")    # Used for debugging information
logging.info("General information")   # Used for informational messages
logging.warning("Something looks off") # Used for warnings
logging.error("An error occurred")    # Used for error reporting
logging.critical("System failure!")   # Used for serious failures

4. Custom Log Formatting

Customizing logs with timestamp, level, and message format:

logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.INFO
)
logging.info("Custom formatted log message")

Example Output:

2025-05-05 12:45:30 - INFO - Custom formatted log message

Writing Logs to a File

Instead of displaying logs in the console, logs can be stored in a file:

logging.basicConfig(
    filename="app.log",
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

logging.info("This log is saved in a file!")

The log will be written to app.log.

Using Loggers for Modular Logging

Creating a Custom Logger

logger = logging.getLogger("custom_logger")  # Create a named logger
logger.setLevel(logging.DEBUG)

# Create a handler for logging to a file
file_handler = logging.FileHandler("custom.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

logger.debug("This debug log is recorded in custom.log")

This method ensures modular logging across different parts of a program.

Using Logging in a Real-World Application

Example: API Request Logging

import logging
import requests

logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)

def fetch_data(url):
    logging.info(f"Fetching data from {url}")
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise error for failed requests
        logging.info(f"Received response: {response.status_code}")
        return response.json()
    except requests.exceptions.RequestException as e:
        logging.error(f"Request failed: {e}")

data = fetch_data("https://api.github.com")

Example Output

2025-05-05 12:50:15 - INFO - Fetching data from https://api.github.com
2025-05-05 12:50:15 - INFO - Received response: 200

More from this blog

Naveen P.N's Tech Blog

94 posts