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.")
๐ Output:
INFO:root:This is an info message.
๐ 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.")
๐ Output:
database - DEBUG - Connecting to the database...
user - INFO - User logged in successfully.
๐งฉ Code Explanation: Logging with Multiple Loggers
import logging
๐น 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)
๐น 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 toDEBUG, meaning this logger will capture all messages fromDEBUGlevel and above (DEBUG, INFO, WARNING, ERROR, CRITICAL).
user_logger = logging.getLogger('user')
user_logger.setLevel(logging.INFO)
๐น What it does:
- Creates another logger named
'user'for user-related operations. - Sets its level to
INFO, so it will ignoreDEBUGmessages and only logINFOand higher levels.
๐บ Creating a Console Handler
console_handler = logging.StreamHandler()
๐น 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)
๐น 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.
๐ Connecting Loggers to the Handler
db_logger.addHandler(console_handler)
user_logger.addHandler(console_handler)
๐น 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.")
๐น 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)
๐ 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.
๐ง 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)