1. import os
  2. import time
  3. import logging
  4. def release_log_resources(log_dir, max_age_days=30, fallback_action="warn"):
  5. """
  6. Releases resources of log files older than max_age_days.
  7. Args:
  8. log_dir (str): The directory containing the log files.
  9. max_age_days (int): The maximum age of log files in days.
  10. fallback_action (str): "warn", "error", or "ignore".
  11. Determines the action if deletion fails.
  12. """
  13. now = time.time()
  14. cutoff_time = now - (max_age_days * 24 * 60 * 60) # Calculate cutoff time
  15. for filename in os.listdir(log_dir):
  16. if filename.endswith(".log"):
  17. filepath = os.path.join(log_dir, filename)
  18. try:
  19. # Get file modification time
  20. file_modified_time = os.path.getmtime(filepath)
  21. # Check if the file is older than the cutoff
  22. if file_modified_time < cutoff_time:
  23. try:
  24. os.remove(filepath) # Delete the file
  25. print(f"Deleted log file: {filepath}")
  26. except OSError as e:
  27. if fallback_action == "warn":
  28. logging.warning(f"Failed to delete {filepath}: {e}")
  29. elif fallback_action == "error":
  30. logging.error(f"Failed to delete {filepath}: {e}")
  31. elif fallback_action == "ignore":
  32. pass # Do nothing
  33. else:
  34. logging.error(f"Invalid fallback action: {fallback_action}")
  35. except OSError as e:
  36. if fallback_action == "warn":
  37. logging.warning(f"Failed to get modification time for {filepath}: {e}")
  38. elif fallback_action == "error":
  39. logging.error(f"Failed to get modification time for {filepath}: {e}")
  40. elif fallback_action == "ignore":
  41. pass
  42. else:
  43. logging.error(f"Invalid fallback action: {fallback_action}")
  44. if __name__ == "__main__":
  45. # Example usage
  46. log_directory = "legacy_logs" # Replace with your log directory
  47. # Create the directory if it doesn't exist
  48. if not os.path.exists(log_directory):
  49. os.makedirs(log_directory)
  50. # Create some dummy log files for testing
  51. with open(os.path.join(log_directory, "log1.log"), "w") as f:
  52. f.write("This is log file 1")
  53. time.sleep(35)
  54. with open(os.path.join(log_directory, "log2.log"), "w") as f:
  55. f.write("This is log file 2")
  56. time.sleep(5)
  57. release_log_resources(log_directory, max_age_days=30, fallback_action="warn")

Add your comment