import os
import time
import logging
def release_log_resources(log_dir, max_age_days=30, fallback_action="warn"):
"""
Releases resources of log files older than max_age_days.
Args:
log_dir (str): The directory containing the log files.
max_age_days (int): The maximum age of log files in days.
fallback_action (str): "warn", "error", or "ignore".
Determines the action if deletion fails.
"""
now = time.time()
cutoff_time = now - (max_age_days * 24 * 60 * 60) # Calculate cutoff time
for filename in os.listdir(log_dir):
if filename.endswith(".log"):
filepath = os.path.join(log_dir, filename)
try:
# Get file modification time
file_modified_time = os.path.getmtime(filepath)
# Check if the file is older than the cutoff
if file_modified_time < cutoff_time:
try:
os.remove(filepath) # Delete the file
print(f"Deleted log file: {filepath}")
except OSError as e:
if fallback_action == "warn":
logging.warning(f"Failed to delete {filepath}: {e}")
elif fallback_action == "error":
logging.error(f"Failed to delete {filepath}: {e}")
elif fallback_action == "ignore":
pass # Do nothing
else:
logging.error(f"Invalid fallback action: {fallback_action}")
except OSError as e:
if fallback_action == "warn":
logging.warning(f"Failed to get modification time for {filepath}: {e}")
elif fallback_action == "error":
logging.error(f"Failed to get modification time for {filepath}: {e}")
elif fallback_action == "ignore":
pass
else:
logging.error(f"Invalid fallback action: {fallback_action}")
if __name__ == "__main__":
# Example usage
log_directory = "legacy_logs" # Replace with your log directory
# Create the directory if it doesn't exist
if not os.path.exists(log_directory):
os.makedirs(log_directory)
# Create some dummy log files for testing
with open(os.path.join(log_directory, "log1.log"), "w") as f:
f.write("This is log file 1")
time.sleep(35)
with open(os.path.join(log_directory, "log2.log"), "w") as f:
f.write("This is log file 2")
time.sleep(5)
release_log_resources(log_directory, max_age_days=30, fallback_action="warn")
Add your comment