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)