Python logging - 2
1️⃣ Logging in a Function (Basic Use Case)
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
📌 error.log File Output
error.log File Output3️⃣ Rotating Log Files (Avoid Large Log Files)
📌 How It Works
4️⃣ Logging to JSON File (Structured Logs)
📌 logs.json Output
logs.json Output5️⃣ Logging in a Flask Application
📌 Output in flask_app.log
flask_app.log6️⃣ Sending Logs via Email
7️⃣ Multi-Module Logging (Logging in Multiple Files)
📜 main.py
main.py📜 module.py
module.py📌 Output
Last updated