1. import json
  2. def process_log_stream(log_stream, fixes, fallback_handler):
  3. """
  4. Processes a log stream with nested structures, applying fixes and falling back if needed.
  5. Args:
  6. log_stream (dict): The log stream data.
  7. fixes (list): A list of fix functions.
  8. fallback_handler (callable): A function to handle cases where fixes fail.
  9. Returns:
  10. dict: The processed log stream, or None if all fixes fail.
  11. """
  12. for fix in fixes:
  13. try:
  14. processed_stream = fix(log_stream) # Apply the fix
  15. if processed_stream:
  16. return processed_stream # Fix successful, return the result
  17. except Exception as e:
  18. print(f"Fix failed: {e}")
  19. pass # Continue to the next fix
  20. # No fixes succeeded, call the fallback handler
  21. return fallback_handler(log_stream)
  22. def example_fix_1(log_stream):
  23. """Example fix function - modifies the log stream."""
  24. if 'error_code' in log_stream and log_stream['error_code'] == 'ERR_001':
  25. log_stream['status'] = 'resolved'
  26. return log_stream
  27. return None
  28. def example_fix_2(log_stream):
  29. """Example fix function - adds a new field."""
  30. if 'message' in log_stream:
  31. log_stream['timestamp'] = '2024-01-01T00:00:00Z' # Add timestamp
  32. return log_stream
  33. return None
  34. def example_fallback(log_stream):
  35. """Example fallback handler - logs the original stream."""
  36. print("Fallback: Log stream could not be processed.")
  37. print(json.dumps(log_stream, indent=2))
  38. return None
  39. if __name__ == '__main__':
  40. # Example usage
  41. log_data = {
  42. 'message': 'An error occurred.',
  43. 'error_code': 'ERR_001',
  44. 'timestamp': '2024-01-01T12:00:00Z'
  45. }
  46. fixes = [example_fix_1, example_fix_2]
  47. fallback_handler = example_fallback
  48. processed_data = process_log_stream(log_data, fixes, fallback_handler)
  49. if processed_data:
  50. print("Processed Log Data:")
  51. print(json.dumps(processed_data, indent=2))
  52. else:
  53. print("Log stream processing failed.")

Add your comment