1. import time
  2. import os
  3. import re
  4. import argparse
  5. def analyze_log_file(log_file_path, patterns=None, ignore_lines=None):
  6. """
  7. Analyzes a log file for specified patterns and measures performance.
  8. """
  9. start_time = time.time()
  10. total_lines = 0
  11. matched_lines = 0
  12. if not os.path.exists(log_file_path):
  13. raise FileNotFoundError(f"Log file not found: {log_file_path}")
  14. try:
  15. with open(log_file_path, 'r', encoding='utf-8') as f:
  16. for line in f:
  17. total_lines += 1
  18. if ignore_lines:
  19. if not any(re.search(pattern, line) for pattern in ignore_lines):
  20. continue # Skip lines matching ignore patterns
  21. if patterns:
  22. for pattern in patterns:
  23. if re.search(pattern, line):
  24. matched_lines += 1
  25. break # Avoid counting same line multiple times
  26. except Exception as e:
  27. raise IOError(f"Error reading log file: {e}")
  28. end_time = time.time()
  29. duration = end_time - start_time
  30. if total_lines == 0:
  31. return {
  32. "total_lines": 0,
  33. "matched_lines": 0,
  34. "duration": duration,
  35. "error": "Log file is empty"
  36. }
  37. match_rate = (matched_lines / total_lines) * 100
  38. return {
  39. "total_lines": total_lines,
  40. "matched_lines": matched_lines,
  41. "duration": duration,
  42. "match_rate": match_rate
  43. }
  44. def main():
  45. """
  46. Main function to parse arguments and run the analysis.
  47. """
  48. parser = argparse.ArgumentParser(description="Analyze log file performance.")
  49. parser.add_argument("log_file", help="Path to the log file.")
  50. parser.add_argument("-p", "--patterns", nargs='+', help="Regular expression patterns to search for.")
  51. parser.add_argument("-i", "--ignore", nargs='+', help="Regular expression patterns to ignore.")
  52. args = parser.parse_args()
  53. try:
  54. analysis_result = analyze_log_file(args.log_file, args.patterns, args.ignore)
  55. print(f"Total lines: {analysis_result['total_lines']}")
  56. print(f"Matched lines: {analysis_result['matched_lines']}")
  57. print(f"Duration: {analysis_result['duration']:.4f} seconds")
  58. print(f"Match rate: {analysis_result['match_rate']:.2f}%")
  59. except FileNotFoundError as e:
  60. print(f"Error: {e}")
  61. except IOError as e:
  62. print(f"Error: {e}")
  63. except Exception as e:
  64. print(f"An unexpected error occurred: {e}")
  65. if __name__ == "__main__":
  66. main()

Add your comment