1. import functools
  2. import logging
  3. import time
  4. from typing import Callable, Any
  5. # Configure logging
  6. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  7. def instrument_response(func: Callable) -> Callable:
  8. """
  9. Decorator to instrument HTTP response handling for maintenance.
  10. Logs response details and execution time.
  11. """
  12. @functools.wraps(func)
  13. def wrapper(*args, **kwargs) -> Any:
  14. """Wrapper function to instrument the original function."""
  15. start_time = time.time()
  16. try:
  17. response = func(*args, **kwargs) # Execute the original function
  18. end_time = time.time()
  19. execution_time = end_time - start_time
  20. logging.info(f"Response from {func.__name__}: Status Code - {response.status_code}, Time taken - {execution_time:.4f} seconds")
  21. return response
  22. except Exception as e:
  23. logging.error(f"Error in {func.__name__}: {e}")
  24. raise # Re-raise the exception to avoid masking the error
  25. return wrapper

Add your comment