Published on August 08, 2024By DeveloperBreeze

Python Logging Snippet

This snippet sets up a logger that writes log messages to both the console and a file, with different log levels to capture various types of information.

import logging
import os

# Create a directory for logs if it doesn't exist
if not os.path.exists('logs'):
    os.makedirs('logs')

# Configure the logger
logging.basicConfig(
    level=logging.DEBUG,  # Set the logging level
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/app.log'),  # Log to a file
        logging.StreamHandler()               # Log to the console
    ]
)

# Get the logger instance
logger = logging.getLogger('MyAppLogger')

# Example usage of the logger
def divide_numbers(x, y):
    try:
        logger.debug(f"Attempting to divide {x} by {y}")
        result = x / y
        logger.info(f"Division successful: {result}")
        return result
    except ZeroDivisionError as e:
        logger.error("Division by zero error", exc_info=True)
    except Exception as e:
        logger.exception("An unexpected error occurred")

# Demonstrate logging in action
if __name__ == "__main__":
    divide_numbers(10, 2)  # Normal operation
    divide_numbers(10, 0)  # Division by zero

Explanation

  • Log Levels: The logger is configured with different log levels:

- DEBUG: Detailed information, typically of interest only when diagnosing problems.

- INFO: Confirmation that things are working as expected.

- ERROR: A more serious problem, which prevented the program from completing a function.

- EXCEPTION: Similar to ERROR, but logs exception information.

  • Logging Handlers: The logging module is configured to handle logging in two ways:

- FileHandler: Writes logs to a file (logs/app.log), useful for long-term storage and analysis.

- StreamHandler: Outputs logs to the console, providing immediate feedback.

  • Logging Format: The format for log messages includes the timestamp, logger name, log level, and message.

  • Error Handling: The code demonstrates how to log exceptions with stack traces using exc_info=True or the exception() method.

Usage

  • Add Logging to Your Application: Use this snippet to quickly integrate logging into any Python application.

  • Monitor Application Behavior: By capturing logs, you can gain insights into application behavior, identify issues, and understand the flow of operations.

  • Debugging: Use DEBUG and INFO logs to follow the logic and data flow through your application.

  • Auditing: Keep track of important operations, errors, and exceptions for auditing purposes.

Logging is a fundamental aspect of software development, helping developers understand and maintain complex systems effectively. This snippet provides a robust starting point for adding logging capabilities to your applications.

Comments

Please log in to leave a comment.

Continue Reading:

File Upload

Published on January 26, 2024

php

Fetching Chuck Norris Jokes from API in JavaScript

Published on January 26, 2024

javascript

React Custom Hook for API Requests

Published on August 12, 2024

javascript

Solidity Cheatsheet

Published on August 22, 2024

solidity

Getting Started with Axios in JavaScript

Published on September 02, 2024

javascript

Advanced JavaScript Tutorial for Experienced Developers

Published on September 02, 2024

javascript

AJAX with JavaScript: A Practical Guide

Published on September 18, 2024

javascript