import logging
import datetime
# Configure logging for non-production use
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='non_production.log', # Log to a file
filemode='a') # Append to the log file
def safe_operation(operation_name, operation_details, *args, **kwargs):
"""
Logs the details of a safe operation, including defensive checks.
"""
try:
# Defensive check: Check for invalid input (e.g., empty strings, negative numbers)
if not operation_details:
raise ValueError("Operation details cannot be empty.")
# Perform the operation
result = operation_name(*args, **kwargs)
# Log the operation with details
logging.info(f"Operation '{operation_name.__name__}' successful. Result: {result}")
return result
except Exception as e:
# Log the error with details
logging.error(f"Operation '{operation_name.__name__}' failed: {e}", exc_info=True) #Include traceback
return None # Or raise the exception, depending on desired behavior
if __name__ == '__main__':
# Example usage
def add(x, y):
return x + y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y
#Safe operation examples
safe_operation(add, "Adding 5 and 3", 5, 3)
safe_operation(divide, "Dividing 10 by 2", 10, 2)
safe_operation(divide, "Dividing 10 by 0", 10, 0) #This will log an error
#Example with invalid input
safe_operation(add, "", 5) #This will log an error
Add your comment