import time
import os
import logging
def retry_log_operation(filepath, operation, max_retries=3, timeout=10):
"""
Retries an operation on a log file with a timeout.
Args:
filepath (str): Path to the log file.
operation (callable): Function to perform on the log file.
max_retries (int): Maximum number of retries.
timeout (int): Timeout in seconds for each retry.
Returns:
The result of the operation if successful, None otherwise.
"""
for attempt in range(max_retries):
try:
# Attempt the operation
result = operation(filepath)
logging.info(f"Operation successful on attempt {attempt + 1}")
return result
except Exception as e:
logging.warning(f"Operation failed on attempt {attempt + 1}: {e}")
if attempt < max_retries - 1:
logging.info(f"Retrying in {timeout} seconds...")
time.sleep(timeout)
else:
logging.error(f"Operation failed after {max_retries} attempts.")
return None
def read_log_file_with_timeout(filepath, timeout):
"""Reads a log file, retrying if it fails."""
def read_file(file_path):
try:
with open(file_path, 'r') as f:
content = f.read()
return content
except Exception as e:
raise e # Re-raise to be handled by retry_log_operation
return retry_log_operation(filepath, read_file, timeout=timeout)
def parse_log_file_with_timeout(filepath, parsing_function, timeout):
"""Parses a log file, retrying if it fails."""
def parse_file(file_path):
try:
return parsing_function(file_path)
except Exception as e:
raise e # Re-raise to be handled by retry_log_operation
return retry_log_operation(filepath, parse_file, timeout=timeout)
if __name__ == '__main__':
#Example Usage
log_file = "my_log.txt"
#Create a dummy log file for testing
with open(log_file, "w") as f:
f.write("This is a log entry.\n")
# Example 1: Read the log file
content = read_log_file_with_timeout(log_file, timeout=5)
if content:
print("Log file content:")
print(content)
else:
print("Failed to read log file after retries.")
# Example 2: Parse the log file
def parse_line(line):
return line.split(',')
parsed_data = parse_log_file_with_timeout(log_file, parse_line, timeout=5)
if parsed_data:
print("Parsed data:")
print(parsed_data)
else:
print("Failed to parse log file after retries.")
#Clean up the dummy log file
os.remove(log_file)
Add your comment