1. import os
  2. import re
  3. import argparse
  4. def cleanup_log_artifacts(log_file, artifact_pattern, artifact_directory, verbose=False):
  5. """
  6. Cleans up artifacts from log entries based on a regex pattern.
  7. Args:
  8. log_file (str): Path to the log file.
  9. artifact_pattern (str): Regex pattern to identify artifacts.
  10. artifact_directory (str): Directory to move artifacts to.
  11. verbose (bool): If True, print actions taken.
  12. """
  13. try:
  14. if not os.path.exists(artifact_directory):
  15. os.makedirs(artifact_directory)
  16. with open(log_file, 'r') as f:
  17. for line in f:
  18. match = re.search(artifact_pattern, line)
  19. if match:
  20. artifact = match.group(1) # Extract the artifact name
  21. artifact_filename = f"{artifact}.log"
  22. artifact_path = os.path.join(artifact_directory, artifact_filename)
  23. if os.path.exists(artifact_path):
  24. try:
  25. os.remove(artifact_path) # Remove existing artifact
  26. except OSError as e:
  27. print(f"Error removing {artifact_path}: {e}")
  28. continue
  29. try:
  30. with open(artifact_path, 'w') as outfile:
  31. outfile.write(line) #copy the line to artifact.
  32. if verbose:
  33. print(f"Artifact '{artifact}' cleaned and moved to '{artifact_path}'")
  34. except OSError as e:
  35. print(f"Error creating/writing to {artifact_path}: {e}")
  36. except FileNotFoundError:
  37. print(f"Error: Log file '{log_file}' not found.")
  38. except Exception as e:
  39. print(f"An unexpected error occurred: {e}")
  40. if __name__ == "__main__":
  41. parser = argparse.ArgumentParser(description="Cleanup artifacts from log entries.")
  42. parser.add_argument("log_file", help="Path to the log file.")
  43. parser.add_argument("artifact_pattern", help="Regex pattern to identify artifacts (group 1 is the artifact name).")
  44. parser.add_argument("artifact_directory", help="Directory to move artifacts to.")
  45. parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output.")
  46. args = parser.parse_args()
  47. cleanup_log_artifacts(args.log_file, args.artifact_pattern, args.artifact_directory, args.verbose)

Add your comment