1. import argparse
  2. import re
  3. def convert_log(input_file, output_file, version="1.0"):
  4. """
  5. Converts log files from older formats to a newer format.
  6. Supports version 1.0 and older formats.
  7. """
  8. try:
  9. with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
  10. for line in infile:
  11. if version == "1.0":
  12. # Example conversion for version 1.0
  13. # Assuming older format: "Timestamp - Message"
  14. match = re.match(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (.*)", line)
  15. if match:
  16. timestamp = match.group(1)
  17. message = match.group(2)
  18. outfile.write(f"[{timestamp}] {message}\n")
  19. else:
  20. outfile.write(line) # Write unchanged if no match
  21. elif version == "0.9":
  22. # Example conversion for version 0.9
  23. # Assuming older format: "Date: Message"
  24. match = re.match(r"Date: (.*)", line)
  25. if match:
  26. date_message = match.group(1)
  27. parts = date_message.split(" ")
  28. if len(parts) >= 2:
  29. date = parts[0]
  30. message = " ".join(parts[1:])
  31. outfile.write(f"[{date}] {message}\n")
  32. else:
  33. outfile.write(line)
  34. else:
  35. outfile.write(line)
  36. else:
  37. outfile.write(line) # Pass through if version not supported
  38. except FileNotFoundError:
  39. print(f"Error: Input file '{input_file}' not found.")
  40. except Exception as e:
  41. print(f"An error occurred: {e}")
  42. if __name__ == "__main__":
  43. parser = argparse.ArgumentParser(description="Convert log files to a newer format.")
  44. parser.add_argument("input_file", help="Path to the input log file.")
  45. parser.add_argument("output_file", help="Path to the output log file.")
  46. parser.add_argument("--version", default="1.0", help="Version of the log format to convert to (default: 1.0). Supported versions: 0.9, 1.0")
  47. args = parser.parse_args()
  48. convert_log(args.input_file, args.output_file, args.version)

Add your comment