import os
import re
import argparse
def cleanup_log_artifacts(log_file, artifact_pattern, artifact_directory, verbose=False):
"""
Cleans up artifacts from log entries based on a regex pattern.
Args:
log_file (str): Path to the log file.
artifact_pattern (str): Regex pattern to identify artifacts.
artifact_directory (str): Directory to move artifacts to.
verbose (bool): If True, print actions taken.
"""
try:
if not os.path.exists(artifact_directory):
os.makedirs(artifact_directory)
with open(log_file, 'r') as f:
for line in f:
match = re.search(artifact_pattern, line)
if match:
artifact = match.group(1) # Extract the artifact name
artifact_filename = f"{artifact}.log"
artifact_path = os.path.join(artifact_directory, artifact_filename)
if os.path.exists(artifact_path):
try:
os.remove(artifact_path) # Remove existing artifact
except OSError as e:
print(f"Error removing {artifact_path}: {e}")
continue
try:
with open(artifact_path, 'w') as outfile:
outfile.write(line) #copy the line to artifact.
if verbose:
print(f"Artifact '{artifact}' cleaned and moved to '{artifact_path}'")
except OSError as e:
print(f"Error creating/writing to {artifact_path}: {e}")
except FileNotFoundError:
print(f"Error: Log file '{log_file}' not found.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Cleanup artifacts from log entries.")
parser.add_argument("log_file", help="Path to the log file.")
parser.add_argument("artifact_pattern", help="Regex pattern to identify artifacts (group 1 is the artifact name).")
parser.add_argument("artifact_directory", help="Directory to move artifacts to.")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output.")
args = parser.parse_args()
cleanup_log_artifacts(args.log_file, args.artifact_pattern, args.artifact_directory, args.verbose)
Add your comment