Manage Old Log Files
Description
The manage_old_files
function manages log files in a specified folder by deleting the oldest files, keeping only the most recent ones. This is useful for log file rotation or limiting disk space usage.
Function Signature:
def manage_old_files(folder_path: str, files_to_keep: int = 20, file_extension: str = '.log') -> None:
Parameters
- folder_path (str): The folder where the log files are stored.
- files_to_keep (int): The number of most recent log files to keep. Default is 20.
- file_extension (str): The file extension of the logs to manage. Default is
.log
.
Returns
- None: The function does not return any value.
Example Usage
manage_old_files("/path/to/logs", files_to_keep=30, file_extension='.txt')
Notes
- The function lists all log files (by default
.log
files) in the specified folder. - Files are sorted by modification time, and the oldest ones are deleted until only the most recent
files_to_keep
are retained.
Error Handling
- If any error occurs (e.g., permission issues, failure to read the directory), the function will print the error message.