Python logging - 2

1️⃣ Logging in a Function (Basic Use Case)

If you want to log function execution, use:

import logging

# Configure logging
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")

def divide(a, b):
    logging.info(f"Dividing {a} by {b}")
    try:
        result = a / b
        logging.debug(f"Result: {result}")
        return result
    except ZeroDivisionError:
        logging.error("Attempted to divide by zero!", exc_info=True)
        return None

# Run function
divide(10, 2)
divide(10, 0)

📌 Output


2️⃣ Logging Exceptions to a File

If you want to log only errors to a file:

📌 error.log File Output


3️⃣ Rotating Log Files (Avoid Large Log Files)

If you want to limit log file size and rotate old logs:

📌 How It Works

  • When rotating.log reaches 1KB, it renames it as rotating.log.1, rotating.log.2, etc.

  • It keeps only the last 3 logs.


4️⃣ Logging to JSON File (Structured Logs)

If you want to log structured JSON logs for debugging:

📌 logs.json Output


5️⃣ Logging in a Flask Application

For Flask apps, you can use logging to track errors and requests:

📌 Output in flask_app.log


6️⃣ Sending Logs via Email

If you want to receive critical logs via email, use:

📌 ⚠️ Note: You may need to enable less secure apps in your email settings or use an app password.


7️⃣ Multi-Module Logging (Logging in Multiple Files)

If you have multiple Python files, you can share the same logger.

📜 main.py

📜 module.py

📌 Output

Last updated