import json
def process_log_stream(log_stream, fixes, fallback_handler):
"""
Processes a log stream with nested structures, applying fixes and falling back if needed.
Args:
log_stream (dict): The log stream data.
fixes (list): A list of fix functions.
fallback_handler (callable): A function to handle cases where fixes fail.
Returns:
dict: The processed log stream, or None if all fixes fail.
"""
for fix in fixes:
try:
processed_stream = fix(log_stream) # Apply the fix
if processed_stream:
return processed_stream # Fix successful, return the result
except Exception as e:
print(f"Fix failed: {e}")
pass # Continue to the next fix
# No fixes succeeded, call the fallback handler
return fallback_handler(log_stream)
def example_fix_1(log_stream):
"""Example fix function - modifies the log stream."""
if 'error_code' in log_stream and log_stream['error_code'] == 'ERR_001':
log_stream['status'] = 'resolved'
return log_stream
return None
def example_fix_2(log_stream):
"""Example fix function - adds a new field."""
if 'message' in log_stream:
log_stream['timestamp'] = '2024-01-01T00:00:00Z' # Add timestamp
return log_stream
return None
def example_fallback(log_stream):
"""Example fallback handler - logs the original stream."""
print("Fallback: Log stream could not be processed.")
print(json.dumps(log_stream, indent=2))
return None
if __name__ == '__main__':
# Example usage
log_data = {
'message': 'An error occurred.',
'error_code': 'ERR_001',
'timestamp': '2024-01-01T12:00:00Z'
}
fixes = [example_fix_1, example_fix_2]
fallback_handler = example_fallback
processed_data = process_log_stream(log_data, fixes, fallback_handler)
if processed_data:
print("Processed Log Data:")
print(json.dumps(processed_data, indent=2))
else:
print("Log stream processing failed.")
Add your comment