本篇和大家分享的是一個清除過期日志的python腳本,年後第二篇希望對大家有幫助;
- 該python腳本建立的由來
- 代碼及分析
- crontab定時任務
此由來,是在過年假期時突然被回報告警伺服器磁盤空間占用比例增大,當時通過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
# 要清除文本的磁盤 "D:/my_project/my_test/logs/mendian_platform/task/2018-09/26",
clearDirs = ["/data1/data/applogs/xxl-job-web"]
doFile = DoFile()
doFile.doFiles(clearDirs, True,3)
其邏輯可以分為下面幾步:
- 從doFiles進入,先去擷取配置的clearDirs數組中的日志所在磁盤路徑下面的日志檔案
- 擷取待删除的檔案,這些檔案以.log字尾結尾,并且通過時間限定政策【目前時間+(-n天) > 文本日志建立時間】來識别哪些到期該删除了
- 最後通過執行rm -rf指令直接删除符合時間政策的日志檔案
上面隻有了清除日志的py腳本,但是要定時執行該腳本才能到達自動的目的,不然每次都手動運作py腳本和直接手動删除日志檔案沒上面太大的差別和省時間,是以這裡用到了crontab任務;編輯cron任務如下指令:
crontab -e
編輯cron任務,往裡面添加定時每周或者每天執行上面的python腳本
0 0 */1 * * python /abc/python/clearDirLog.py > /abc/python/dolog.log 2>&1
上面cron表達式意思:定時每天執行一次clearDirLog.py腳本,并把clearDirLog.py裡面列印出來的資訊記錄到dolog.log檔案中;
編輯任務儲存後,我們可以通過如下指令檢視cron的任務清單:
crontab -l