DeveloperBreeze

Python Development Development Tutorials, Guides & Insights

Unlock 2+ expert-curated python development tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your python development skills on DeveloperBreeze.

Setting Up and Managing Python Virtual Environments Using venv

Tutorial August 29, 2024
python

pip freeze > requirements.txt

To install the dependencies listed in a requirements.txt file, run:

Python Logging Snippet

Code August 08, 2024
python

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

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