import os
import time
from pathlib import Path
def clean_logs(log_dir, days_to_keep, pattern='*.log'):
# 获取当前时间戳
now = time.time()
# 将日志目录转换为 Path 对象
log_path = Path(log_dir)
# 遍历匹配的文件
for file in log_path.glob(pattern):
if file.is_file():
# 获取文件的修改时间
file_mtime = file.stat().st_mtime
# 计算文件存在的天数
age_in_days = (now - file_mtime) / (60 * 60 * 24)
if age_in_days > days_to_keep:
print(f"Deleting old log file: {file}")
try:
# 删除旧日志文件
file.unlink()
except Exception as e:
print(f"Error deleting {file}: {e}")
if __name__ == "__main__":
# 日志目录,需要根据实际情况修改
log_directory = './logs'
# 日志保留天数
days_to_keep_logs = 7
# 调用清理函数
clean_logs(log_directory, days_to_keep_logs)
你可以按照以下步骤使用这个脚本:
- 将上述代码保存为 clean_logs.py 。
- 修改 log_directory 变量为你的日志文件所在目录。
- 修改 days_to_keep_logs 变量为你想要保留日志的天数。
- 在终端中运行以下命令来执行脚本:
python3 clean_logs.py
如果你想定时执行这个脚本,可以使用 cron 任务。在终端中输入 crontab -e ,然后添加以下内容来每天凌晨 2 点执行脚本:
0 2 * * * /usr/bin/python3 /path/to/clean_logs.py
请将 /path/to/clean_logs.py 替换为你实际保存脚本的路径