本篇和你們分享的是一個清除過時日誌的python腳本,年後第二篇但願對你們有幫助;python
此由來,是在過年假期時忽然被反饋告警服務器磁盤空間佔用比例增大,當時經過df等命令定位到,是使用了某個開源任務調度框架日誌增大並以前不少歷史日誌沒有自動刪除致使的;web
所以,查看該框架的文檔是否有自動清除配置,暫時沒有找到自動清除日誌的配置說明,因而乎瀏覽源碼就是log4來記錄的,原本打算擴展重寫下log4讓其具備自動清除日誌的功能,可是想到之後可能還有其餘項目的日誌沒法自動清除,因而乎有了本篇分享的python產出,僅僅配置下檢測路徑便可刪除自定義n天以前的日誌數組
先來上代碼,具體以下:服務器
1 #! /usr/bin/python 2 #coding=utf-8 3 import os 4 import datetime 5 import time 6 7 8 class DoFile(): 9 # 獲取某個磁盤路徑裏全部文件 10 def getFiles(self, strDir, isLoop, overDay): 11 files = [] 12 if len(strDir) <= 0 or not os.path.exists(strDir): 13 return files 14 dirs = os.listdir(strDir) 15 for dir in dirs: 16 path = os.path.join(strDir, dir) 17 if(os.path.isfile(path) and path.find(".log") >= 0): # 是.log文件 18 if(self.compareFileTime(path, -overDay)): 19 files.append(path) 20 elif(os.path.isdir(path) and isLoop): # 是磁盤 21 files.extend(self.getFiles(path, isLoop, overDay)) 22 else: 23 continue 24 return files 25 26 # 綜合處理磁盤文件 27 def doFiles(self, clearDirs, isLoop=False, overDay=3): 28 print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")+":執行中...") 29 for dir in clearDirs: 30 files = self.getFiles(dir, isLoop, overDay) 31 print("{}查詢出{}個文件".format(dir, len(files))) 32 self.clearFiles(files) 33 print("執行完畢...") 34 35 # 清除文本文件 36 def clearFiles(self, files): 37 for file in files: 38 strcmd = "rm -rf {}".format(file) 39 self.exec_cmd(strcmd) 40 41 #執行腳本命令 42 def exec_cmd(self, strcmd): 43 os.system(strcmd) 44 45 #獲取文件建立時間 46 def getCreateFileTime(self, path): 47 return os.path.getctime(path) 48 49 #時間戳轉datetime 50 def TimeStampToTime(self,timestamp): 51 return datetime.datetime.utcfromtimestamp(timestamp) 52 53 #比較當前時間與文件建立時間差值(天) 54 def compareFileTime(self, path,overDay): 55 comparTime = self.TimeStampToTime(self.getCreateFileTime(path)) 56 now = datetime.datetime.utcnow() + datetime.timedelta(days= overDay) 57 return now > comparTime 58 59 60 # 要清除文本的磁盤 61 clearDirs = ["/data1/data/logs/xxl-job-web"] 62 doFile = DoFile() 63 doFile.doFiles(clearDirs, True,3)
其邏輯能夠分爲下面幾步:app
上面只有了清除日誌的py腳本,可是要定時執行該腳本才能到達自動的目的,否則每次都手動運行py腳本和直接手動刪除日誌文件沒上面太大的區別和省時間,所以這裏用到了crontab任務;編輯cron任務以下命令:框架
1 crontab -e
編輯cron任務,往裏面添加定時每週或者天天執行上面的python腳本oop
1 0 0 */1 * * python /abc/python/clearDirLog.py > /abc/python/dolog.log 2>&1
上面cron表達式意思:定時天天執行一次clearDirLog.py腳本,並把clearDirLog.py裏面打印出來的信息記錄到dolog.log文件中;編輯任務保存後,咱們能夠經過以下命令查看cron的任務列表:spa
1 crontab -l