DEV Community

likhitha manikonda
likhitha manikonda

Posted on

🐍 Mastering Python Logging: A Beginner's Guide

Logging is a powerful tool in Python that helps developers track events during program execution. It’s essential for debugging, monitoring, and understanding how your code behaves in real-world scenarios.


🔹 Logging Practical Implementation in Python

✅ What is Logging?

Logging is the process of recording messages that describe events in your application. These messages can be errors, warnings, or general information.

✨ Basic Logging Example

import logging

# Set up basic configuration
logging.basicConfig(level=logging.INFO)

# Log a message
logging.info("This is an info message.")
Enter fullscreen mode Exit fullscreen mode

🔍 Output:

INFO:root:This is an info message.
Enter fullscreen mode Exit fullscreen mode

🛠 Logging Levels

Python provides five standard logging levels:

  • DEBUG: Detailed information, useful for diagnosing problems.
  • INFO: Confirmation that things are working as expected.
  • WARNING: Something unexpected happened, but the program is still running.
  • ERROR: A serious problem that caused a function to fail.
  • CRITICAL: A very serious error that may prevent the program from continuing.

🔹 Logging with Multiple Loggers

Sometimes, you need different loggers for different parts of your application.

🧪 Example: Multiple Loggers

import logging

# Create logger for database operations
db_logger = logging.getLogger('database')
db_logger.setLevel(logging.DEBUG)

# Create logger for user operations
user_logger = logging.getLogger('user')
user_logger.setLevel(logging.INFO)

# Create console handler
console_handler = logging.StreamHandler()

# Set format
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)

# Add handler to loggers
db_logger.addHandler(console_handler)
user_logger.addHandler(console_handler)

# Log messages
db_logger.debug("Connecting to the database...")
user_logger.info("User logged in successfully.")
Enter fullscreen mode Exit fullscreen mode

🔍 Output:

database - DEBUG - Connecting to the database...
user - INFO - User logged in successfully.
Enter fullscreen mode Exit fullscreen mode

🧩 Code Explanation: Logging with Multiple Loggers

import logging
Enter fullscreen mode Exit fullscreen mode

🔹 What it does: This imports Python’s built-in logging module, which allows you to record messages (logs) during your program’s execution.


🛠 Creating Loggers

db_logger = logging.getLogger('database')
db_logger.setLevel(logging.DEBUG)

Enter fullscreen mode Exit fullscreen mode

🔹 What it does:

  • getLogger('database'): Creates a logger named 'database'. You can think of this as a label for logs related to database operations.
  • setLevel(logging.DEBUG): Sets the logging level to DEBUG, meaning this logger will capture all messages from DEBUG level and above (DEBUG, INFO, WARNING, ERROR, CRITICAL).
user_logger = logging.getLogger('user')
user_logger.setLevel(logging.INFO)
Enter fullscreen mode Exit fullscreen mode

🔹 What it does:

  • Creates another logger named 'user' for user-related operations.
  • Sets its level to INFO, so it will ignore DEBUG messages and only log INFO and higher levels.

📺 Creating a Console Handler

console_handler = logging.StreamHandler()
Enter fullscreen mode Exit fullscreen mode

🔹 What it does: This handler sends log messages to the console (standard output). Think of it as the “delivery system” for your logs.


🎨 Formatting the Logs

formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
Enter fullscreen mode Exit fullscreen mode

🔹 What it does:

  • Formatter(...): Defines how the log messages will look.
  • %(name)s: Shows the logger’s name (e.g., 'database' or 'user').
  • %(levelname)s: Shows the severity level (e.g., INFO, DEBUG).
  • %(message)s: Shows the actual log message.

🔹 Example Output:

database - DEBUG - Connecting to the database...
user - INFO - User logged in successfully.
Enter fullscreen mode Exit fullscreen mode

🔗 Connecting Loggers to the Handler

db_logger.addHandler(console_handler)
user_logger.addHandler(console_handler)
Enter fullscreen mode Exit fullscreen mode

🔹 What it does: Attaches the console_handler to both loggers so their messages will be printed to the console using the defined format.


🧾 Logging Messages

db_logger.debug("Connecting to the database...")
user_logger.info("User logged in successfully.")
Enter fullscreen mode Exit fullscreen mode

🔹 What it does:

  • db_logger.debug(...): Logs a debug message about connecting to the database.
  • user_logger.info(...): Logs an info message about a successful user login.

✅ Summary

  • You created two separate loggers for different parts of your application.
  • Each logger has its own logging level.
  • You used a console handler to display logs.
  • You formatted the logs for clarity.
  • You logged messages using appropriate severity levels.

🔹 Logging with a Real World Example

Let’s simulate a simple e-commerce checkout system.

🛒 Example: E-commerce Checkout

import logging

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

def process_payment(amount):
    if amount <= 0:
        logging.error("Invalid payment amount.")
        return False
    logging.info(f"Processing payment of ₹{amount}")
    return True

def checkout(cart_total):
    logging.info("Starting checkout process...")
    success = process_payment(cart_total)
    if success:
        logging.info("Checkout completed successfully.")
    else:
        logging.warning("Checkout failed.")

# Simulate checkout
checkout(500)
checkout(-100)
Enter fullscreen mode Exit fullscreen mode

🔍 Output:

2025-10-25 20:01:23,123 - INFO - Starting checkout process...
2025-10-25 20:01:23,124 - INFO - Processing payment of ₹500
2025-10-25 20:01:23,125 - INFO - Checkout completed successfully.
2025-10-25 20:01:23,126 - INFO - Starting checkout process...
2025-10-25 20:01:23,127 - ERROR - Invalid payment amount.
2025-10-25 20:01:23,128 - WARNING - Checkout failed.
Enter fullscreen mode Exit fullscreen mode

🧠 Final Thoughts

  • Logging helps you understand your application better.
  • Use different log levels to categorize messages.
  • Multiple loggers allow modular logging for large applications.
  • Always format logs for readability and consistency.

Top comments (0)