本篇和大家分享的是一个清除过期日志的 python 脚本, 年后第二篇希望对大家有帮助;
该 python 脚本创建的由来
代码及分析
crontab 定时任务
该 python 脚本创建的由来
此由来, 是在过年假期时突然被反馈告警服务器磁盘空间占用比例增大, 当时通过 df 等命令定位到, 是使用了某个开源任务调度框架日志增大并之前很多历史日志没有自动删除导致的;
因此, 查看该框架的文档是否有自动清除配置, 暂时没有找到自动清除日志的配置说明, 于是乎浏览源码就是 log4 来记录的, 本来打算扩展重写下 log4 让其具有自动清除日志的功能, 但是想到以后可能还有其他项目的日志无法自动清除, 于是乎有了本篇分享的 python 产出, 仅仅配置下检测路径即可删除自定义 n 天之前的日志
代码及分析
先来上代码, 具体如下:
- #! /usr/bin/python
- #coding=utf-8
- import os
- import datetime
- import time
- class DoFile():
- # 获取某个磁盘路径里所有文件
- def getFiles(self, strDir, isLoop, overDay):
- files = []
- if len(strDir) <= 0 or not os.path.exists(strDir):
- return files
- dirs = os.listdir(strDir)
- for dir in dirs:
- path = os.path.join(strDir, dir)
- if(os.path.isfile(path) and path.find(".log")>= 0): # 是. log 文件
- if(self.compareFileTime(path, -overDay)):
- files.append(path)
- elif(os.path.isdir(path) and isLoop): # 是磁盘
- files.extend(self.getFiles(path, isLoop, overDay))
- else:
- continue
- return files
- # 综合处理磁盘文件
- def doFiles(self, clearDirs, isLoop=False, overDay=3):
- print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")+": 执行中...")
- for dir in clearDirs:
- files = self.getFiles(dir, isLoop, overDay)
- print("{}查询出 {} 个文件".format(dir, len(files)))
- self.clearFiles(files)
- print("执行完毕...")
- # 清除文本文件
- def clearFiles(self, files):
- for file in files:
- strcmd = "rm -rf {}".format(file)
- self.exec_cmd(strcmd)
- #执行脚本命令
- def exec_cmd(self, strcmd):
- os.system(strcmd)
- #获取文件创建时间
- def getCreateFileTime(self, path):
- return os.path.getctime(path)
- #时间戳转 datetime
- def TimeStampToTime(self,timestamp):
- return datetime.datetime.utcfromtimestamp(timestamp)
- #比较当前时间与文件创建时间差值(天)
- def compareFileTime(self, path,overDay):
- comparTime = self.TimeStampToTime(self.getCreateFileTime(path))
- now = datetime.datetime.utcnow() + datetime.timedelta(days= overDay)
- return now> comparTime
- # 要清除文本的磁盘 61 clearDirs = ["/data1/data/logs/xxl-job-web"]
- doFile = DoFile()
- doFile.doFiles(clearDirs, True,3)
其逻辑可以分为下面几步:
从 doFiles 进入, 先去获取配置的 clearDirs 数组中的日志所在磁盘路径下面的日志文件
获取待删除的文件, 这些文件以. log 后缀结尾, 并且通过时间限定策略[当前时间 +(-n 天)> 文本日志创建时间] 来识别哪些到期该删除了
最后通过执行 rm -rf 命令直接删除符合时间策略的日志文件
crontab 定时任务
上面只有了清除日志的 py 脚本, 但是要定时执行该脚本才能到达自动的目的, 不然每次都手动运行 py 脚本和直接手动删除日志文件没上面太大的区别和省时间, 因此这里用到了 crontab 任务; 编辑 cron 任务如下命令:
1 crontab -e
编辑 cron 任务, 往里面添加定时每周或者每天执行上面的 python 脚本
1 0 0 */1 * * python /abc/python/clearDirLog.py> /abc/python/dolog.log 2>&1
上面 cron 表达式意思: 定时每天执行一次 clearDirLog.py 脚本, 并把 clearDirLog.py 里面打印出来的信息记录到 dolog.log 文件中; 编辑任务保存后, 我们可以通过如下命令查看 cron 的任务列表:
1 crontab -l
来源: https://www.cnblogs.com/wangrudong003/p/10389181.html