import os
import time
import datetime
import shutil
import logging
def archive_log_files(log_dir, archive_dir, retry_interval=60):
"""
Archives log files from a directory to an archive directory with retry.
Args:
log_dir (str): Path to the directory containing log files.
archive_dir (str): Path to the directory where archived logs will be stored.
retry_interval (int): Retry interval in seconds.
"""
if not os.path.exists(archive_dir):
os.makedirs(archive_dir)
for filename in os.listdir(log_dir):
if filename.endswith(".log"):
log_filepath = os.path.join(log_dir, filename)
archive_filepath = os.path.join(archive_dir, filename)
retries = 0
while retries < 3: # Retry up to 3 times
try:
shutil.move(log_filepath, archive_filepath)
logging.info(f"Archived {filename} to {archive_dir}")
break # Exit retry loop if successful
except Exception as e:
retries += 1
logging.warning(f"Failed to archive {filename} (attempt {retries}/{3}): {e}")
time.sleep(retry_interval)
if retries == 3:
logging.error(f"Failed to archive {filename} after multiple retries.")
if __name__ == '__main__':
# Example usage:
log_directory = "/path/to/your/logs" # Replace with your log directory
archive_directory = "/path/to/your/archive" # Replace with your archive directory
#Create some dummy log files for testing
if not os.path.exists(log_directory):
os.makedirs(log_directory)
with open(os.path.join(log_directory, "test_log1.log"), "w") as f:
f.write("This is test log 1")
with open(os.path.join(log_directory, "test_log2.log"), "w") as f:
f.write("This is test log 2")
archive_log_files(log_directory, archive_directory)
Add your comment