1. import re
  2. def compare_log_entries(log_file, expected_values):
  3. """
  4. Compares log entries from a file against expected values.
  5. Args:
  6. log_file (str): Path to the log file.
  7. expected_values (dict): A dictionary where keys are log entry patterns
  8. (regex) and values are the expected values.
  9. Returns:
  10. list: A list of discrepancies found. Empty list if no discrepancies.
  11. """
  12. discrepancies = []
  13. try:
  14. with open(log_file, 'r') as f:
  15. for line in f:
  16. for pattern, expected in expected_values.items():
  17. match = re.search(pattern, line)
  18. if match:
  19. actual = match.group(1) # Assuming the value is in group 1
  20. if actual != str(expected): #Compare as strings.
  21. discrepancies.append({
  22. 'line': line.strip(),
  23. 'pattern': pattern,
  24. 'expected': expected,
  25. 'actual': actual
  26. })
  27. except FileNotFoundError:
  28. print(f"Error: Log file not found: {log_file}")
  29. return None
  30. return discrepancies
  31. if __name__ == '__main__':
  32. # Example Usage
  33. log_file = 'non_production.log'
  34. expected_values = {
  35. r'User logged in: (.*)': 'testuser',
  36. r'Request processed: (.*)': 'GET /api/data',
  37. r'Error: (.*)': 'Invalid input'
  38. }
  39. # Create a dummy log file for testing
  40. with open(log_file, 'w') as f:
  41. f.write("User logged in: adminuser\n")
  42. f.write("Request processed: POST /api/submit\n")
  43. f.write("Error: Permission denied\n")
  44. f.write("User logged in: testuser\n")
  45. f.write("Request processed: GET /api/data\n")
  46. discrepancies = compare_log_entries(log_file, expected_values)
  47. if discrepancies:
  48. print("Discrepancies found:")
  49. for diff in discrepancies:
  50. print(f" Line: {diff['line']}")
  51. print(f" Pattern: {diff['pattern']}")
  52. print(f" Expected: {diff['expected']}")
  53. print(f" Actual: {diff['actual']}")
  54. print("-" * 20)
  55. else:
  56. print("No discrepancies found.")

Add your comment