1. import json
  2. import logging
  3. import argparse
  4. def flatten_log_stream(log_entry):
  5. """Flattens a single log entry into a single dictionary."""
  6. flat_entry = {}
  7. for key, value in log_entry.items():
  8. if isinstance(value, dict):
  9. for sub_key, sub_value in value.items():
  10. flat_entry[f"{key}_{sub_key}"] = sub_value
  11. elif isinstance(value, list):
  12. for i, item in enumerate(value):
  13. flat_entry[f"{key}_{i}"] = item
  14. else:
  15. flat_entry[key] = value
  16. return flat_entry
  17. def process_log_stream(log_stream, config):
  18. """Processes a log stream and flattens each entry."""
  19. flattened_entries = []
  20. for entry in log_stream:
  21. flattened_entries.append(flatten_log_stream(entry))
  22. return flattened_entries
  23. def main():
  24. """Main function to read config, process log stream, and output."""
  25. parser = argparse.ArgumentParser(description="Flatten log streams.")
  26. parser.add_argument("config_file", help="Path to the configuration file.")
  27. parser.add_argument("log_file", help="Path to the log file.")
  28. parser.add_argument("output_file", help="Path to the output file.")
  29. args = parser.parse_args()
  30. try:
  31. with open(args.config_file, 'r') as f:
  32. config = json.load(f)
  33. except FileNotFoundError:
  34. logging.error(f"Config file not found: {args.config_file}")
  35. return
  36. except json.JSONDecodeError:
  37. logging.error(f"Invalid JSON in config file: {args.config_file}")
  38. return
  39. try:
  40. with open(args.log_file, 'r') as f:
  41. log_stream = json.load(f)
  42. except FileNotFoundError:
  43. logging.error(f"Log file not found: {args.log_file}")
  44. return
  45. except json.JSONDecodeError:
  46. logging.error(f"Invalid JSON in log file: {args.log_file}")
  47. return
  48. flattened_data = process_log_stream(log_stream, config)
  49. try:
  50. with open(args.output_file, 'w') as f:
  51. json.dump(flattened_data, f, indent=4)
  52. except IOError:
  53. logging.error(f"Error writing to output file: {args.output_file}")
  54. return
  55. if __name__ == "__main__":
  56. main()

Add your comment