DeveloperBreeze

Python Logging Snippet

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.

Related Posts

More content you might like

Tutorial
bash

Mastering Advanced Git Workflows for Professional Developers

   git sparse-checkout set path/to/dir

Git hooks allow you to automate tasks during the Git lifecycle.

Dec 10, 2024
Read More
Code
javascript

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

  • serverSide: true enables server-side pagination, sorting, and filtering.
  • processing: true displays a processing indicator while fetching data.
  • The ajax object defines how data is fetched from the server.
  • url: Endpoint for fetching data.
  • type: HTTP method (GET).
  • error: Logs errors that occur during the AJAX request.
  • dataSrc: Processes the server's response. It logs the data and returns records for display.

Oct 24, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

  • Http::post(): This sends a POST request to the specified URL.
  • $response->body(): Returns the raw response body, which can be used as needed.

Some APIs require an API key for authentication. You can pass headers using Laravel’s Http facade easily.

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!