1. import logging
  2. import datetime
  3. # Configure logging for non-production use
  4. logging.basicConfig(level=logging.INFO,
  5. format='%(asctime)s - %(levelname)s - %(message)s',
  6. filename='non_production.log', # Log to a file
  7. filemode='a') # Append to the log file
  8. def safe_operation(operation_name, operation_details, *args, **kwargs):
  9. """
  10. Logs the details of a safe operation, including defensive checks.
  11. """
  12. try:
  13. # Defensive check: Check for invalid input (e.g., empty strings, negative numbers)
  14. if not operation_details:
  15. raise ValueError("Operation details cannot be empty.")
  16. # Perform the operation
  17. result = operation_name(*args, **kwargs)
  18. # Log the operation with details
  19. logging.info(f"Operation '{operation_name.__name__}' successful. Result: {result}")
  20. return result
  21. except Exception as e:
  22. # Log the error with details
  23. logging.error(f"Operation '{operation_name.__name__}' failed: {e}", exc_info=True) #Include traceback
  24. return None # Or raise the exception, depending on desired behavior
  25. if __name__ == '__main__':
  26. # Example usage
  27. def add(x, y):
  28. return x + y
  29. def divide(x, y):
  30. if y == 0:
  31. raise ValueError("Cannot divide by zero.")
  32. return x / y
  33. #Safe operation examples
  34. safe_operation(add, "Adding 5 and 3", 5, 3)
  35. safe_operation(divide, "Dividing 10 by 2", 10, 2)
  36. safe_operation(divide, "Dividing 10 by 0", 10, 0) #This will log an error
  37. #Example with invalid input
  38. safe_operation(add, "", 5) #This will log an error

Add your comment