import time
import os
import re
import argparse
def analyze_log_file(log_file_path, patterns=None, ignore_lines=None):
"""
Analyzes a log file for specified patterns and measures performance.
"""
start_time = time.time()
total_lines = 0
matched_lines = 0
if not os.path.exists(log_file_path):
raise FileNotFoundError(f"Log file not found: {log_file_path}")
try:
with open(log_file_path, 'r', encoding='utf-8') as f:
for line in f:
total_lines += 1
if ignore_lines:
if not any(re.search(pattern, line) for pattern in ignore_lines):
continue # Skip lines matching ignore patterns
if patterns:
for pattern in patterns:
if re.search(pattern, line):
matched_lines += 1
break # Avoid counting same line multiple times
except Exception as e:
raise IOError(f"Error reading log file: {e}")
end_time = time.time()
duration = end_time - start_time
if total_lines == 0:
return {
"total_lines": 0,
"matched_lines": 0,
"duration": duration,
"error": "Log file is empty"
}
match_rate = (matched_lines / total_lines) * 100
return {
"total_lines": total_lines,
"matched_lines": matched_lines,
"duration": duration,
"match_rate": match_rate
}
def main():
"""
Main function to parse arguments and run the analysis.
"""
parser = argparse.ArgumentParser(description="Analyze log file performance.")
parser.add_argument("log_file", help="Path to the log file.")
parser.add_argument("-p", "--patterns", nargs='+', help="Regular expression patterns to search for.")
parser.add_argument("-i", "--ignore", nargs='+', help="Regular expression patterns to ignore.")
args = parser.parse_args()
try:
analysis_result = analyze_log_file(args.log_file, args.patterns, args.ignore)
print(f"Total lines: {analysis_result['total_lines']}")
print(f"Matched lines: {analysis_result['matched_lines']}")
print(f"Duration: {analysis_result['duration']:.4f} seconds")
print(f"Match rate: {analysis_result['match_rate']:.2f}%")
except FileNotFoundError as e:
print(f"Error: {e}")
except IOError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Add your comment