1. import time
  2. import os
  3. import logging
  4. def retry_log_operation(filepath, operation, max_retries=3, timeout=10):
  5. """
  6. Retries an operation on a log file with a timeout.
  7. Args:
  8. filepath (str): Path to the log file.
  9. operation (callable): Function to perform on the log file.
  10. max_retries (int): Maximum number of retries.
  11. timeout (int): Timeout in seconds for each retry.
  12. Returns:
  13. The result of the operation if successful, None otherwise.
  14. """
  15. for attempt in range(max_retries):
  16. try:
  17. # Attempt the operation
  18. result = operation(filepath)
  19. logging.info(f"Operation successful on attempt {attempt + 1}")
  20. return result
  21. except Exception as e:
  22. logging.warning(f"Operation failed on attempt {attempt + 1}: {e}")
  23. if attempt < max_retries - 1:
  24. logging.info(f"Retrying in {timeout} seconds...")
  25. time.sleep(timeout)
  26. else:
  27. logging.error(f"Operation failed after {max_retries} attempts.")
  28. return None
  29. def read_log_file_with_timeout(filepath, timeout):
  30. """Reads a log file, retrying if it fails."""
  31. def read_file(file_path):
  32. try:
  33. with open(file_path, 'r') as f:
  34. content = f.read()
  35. return content
  36. except Exception as e:
  37. raise e # Re-raise to be handled by retry_log_operation
  38. return retry_log_operation(filepath, read_file, timeout=timeout)
  39. def parse_log_file_with_timeout(filepath, parsing_function, timeout):
  40. """Parses a log file, retrying if it fails."""
  41. def parse_file(file_path):
  42. try:
  43. return parsing_function(file_path)
  44. except Exception as e:
  45. raise e # Re-raise to be handled by retry_log_operation
  46. return retry_log_operation(filepath, parse_file, timeout=timeout)
  47. if __name__ == '__main__':
  48. #Example Usage
  49. log_file = "my_log.txt"
  50. #Create a dummy log file for testing
  51. with open(log_file, "w") as f:
  52. f.write("This is a log entry.\n")
  53. # Example 1: Read the log file
  54. content = read_log_file_with_timeout(log_file, timeout=5)
  55. if content:
  56. print("Log file content:")
  57. print(content)
  58. else:
  59. print("Failed to read log file after retries.")
  60. # Example 2: Parse the log file
  61. def parse_line(line):
  62. return line.split(',')
  63. parsed_data = parse_log_file_with_timeout(log_file, parse_line, timeout=5)
  64. if parsed_data:
  65. print("Parsed data:")
  66. print(parsed_data)
  67. else:
  68. print("Failed to parse log file after retries.")
  69. #Clean up the dummy log file
  70. os.remove(log_file)

Add your comment