1. import re
  2. def diagnose_file(filepath, patterns):
  3. """
  4. Matches patterns in a file content and returns matching patterns.
  5. Args:
  6. filepath (str): The path to the file.
  7. patterns (dict): A dictionary where keys are pattern names and values are regular expressions.
  8. Returns:
  9. dict: A dictionary where keys are pattern names and values are lists of matched lines.
  10. Returns an empty dictionary if the file doesn't exist or an error occurs.
  11. """
  12. try:
  13. with open(filepath, 'r') as f:
  14. content = f.read()
  15. except FileNotFoundError:
  16. print(f"Error: File not found at {filepath}")
  17. return {}
  18. except Exception as e:
  19. print(f"Error reading file: {e}")
  20. return {}
  21. results = {}
  22. for name, pattern in patterns.items():
  23. results[name] = re.findall(pattern, content, re.MULTILINE)
  24. return results
  25. if __name__ == '__main__':
  26. # Example usage
  27. patterns = {
  28. "error_messages": r"ERROR: (.*)", # Matches lines starting with "ERROR:"
  29. "warning_messages": r"WARNING: (.*)", # Matches lines starting with "WARNING:"
  30. "log_level": r"log_level=(.*)" # Matches lines containing "log_level="
  31. }
  32. filepath = "example.log" # Replace with your file path
  33. # Create a dummy log file for testing
  34. with open(filepath, "w") as f:
  35. f.write("This is a normal log line.\n")
  36. f.write("ERROR: Something went wrong.\n")
  37. f.write("WARNING: Low disk space.\n")
  38. f.write("log_level=INFO\n")
  39. f.write("Another normal log line.\n")
  40. f.write("ERROR: Another error occurred.\n")
  41. f.write("WARNING: Memory usage is high.\n")
  42. diagnostics = diagnose_file(filepath, patterns)
  43. for name, matches in diagnostics.items():
  44. if matches:
  45. print(f"Pattern: {name}")
  46. for match in matches:
  47. print(match)
  48. else:
  49. print(f"Pattern: {name} - No matches found.")

Add your comment