日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python日志模块备份_Python Logging模块 输出日志颜色、过期清理和日志滚动备份

發(fā)布時(shí)間:2024/7/5 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python日志模块备份_Python Logging模块 输出日志颜色、过期清理和日志滚动备份 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

#coding:utf-8

importloggingfrom logging.handlers importRotatingFileHandler # 按文件大小滾動(dòng)備份import colorlog #控制臺(tái)日志輸入顏色

importtimeimportdatetimeimportos

cur_path= os.path.dirname(os.path.realpath(__file__)) #log_path是存放日志的路徑

log_path = os.path.join(os.path.dirname(cur_path), 'logs')if not os.path.exists(log_path): os.mkdir(log_path) #如果不存在這個(gè)logs文件夾,就自動(dòng)創(chuàng)建一個(gè)

logName = os.path.join(log_path, '%s.log' % time.strftime('%Y-%m-%d')) #文件的命名

log_colors_config={'DEBUG': 'cyan','INFO': 'green','WARNING': 'yellow','ERROR': 'red','CRITICAL': 'red',

}classLog:def __init__(self, logName=logName):

self.logName=logName

self.logger=logging.getLogger()

self.logger.setLevel(logging.DEBUG)

self.formatter=colorlog.ColoredFormatter('%(log_color)s[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s',

log_colors=log_colors_config) #日志輸出格式

self.handle_logs()defget_file_sorted(self, file_path):"""最后修改時(shí)間順序升序排列 os.path.getmtime()->獲取文件最后修改時(shí)間"""dir_list=os.listdir(file_path)if notdir_list:return

else:

dir_list= sorted(dir_list, key=lambdax: os.path.getmtime(os.path.join(file_path, x)))returndir_listdefTimeStampToTime(self, timestamp):"""格式化時(shí)間"""timeStruct=time.localtime(timestamp)return str(time.strftime('%Y-%m-%d', timeStruct))defhandle_logs(self):"""處理日志過期天數(shù)和文件數(shù)量"""dir_list= ['report'] #要?jiǎng)h除文件的目錄名

for dir indir_list:

dirPath= os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + '\\' + dir #拼接刪除目錄完整路徑

file_list = self.get_file_sorted(dirPath) #返回按修改時(shí)間排序的文件list

if file_list: #目錄下沒有日志文件

for i infile_list:

file_path= os.path.join(dirPath, i) #拼接文件的完整路徑

t_list = self.TimeStampToTime(os.path.getctime(file_path)).split('-')

now_list= self.TimeStampToTime(time.time()).split('-')

t= datetime.datetime(int(t_list[0]), int(t_list[1]),

int(t_list[2])) #將時(shí)間轉(zhuǎn)換成datetime.datetime 類型

now = datetime.datetime(int(now_list[0]), int(now_list[1]), int(now_list[2]))if (now - t).days > 6: #創(chuàng)建時(shí)間大于6天的文件刪除

self.delete_logs(file_path)if len(file_list) > 4: #限制目錄下記錄文件數(shù)量

file_list = file_list[0:-4]for i infile_list:

file_path=os.path.join(dirPath, i)print(file_path)

self.delete_logs(file_path)defdelete_logs(self, file_path):try:

os.remove(file_path)exceptPermissionError as e:

Log().warning('刪除日志文件失敗:{}'.format(e))def __console(self, level, message):#創(chuàng)建一個(gè)FileHandler,用于寫到本地

fh = RotatingFileHandler(filename=self.logName, mode='a', maxBytes=1024 * 1024 * 5, backupCount=5,

encoding='utf-8') #使用RotatingFileHandler類,滾動(dòng)備份日志

fh.setLevel(logging.DEBUG)

fh.setFormatter(self.formatter)

self.logger.addHandler(fh)#創(chuàng)建一個(gè)StreamHandler,用于輸出到控制臺(tái)

ch =colorlog.StreamHandler()

ch.setLevel(logging.DEBUG)

ch.setFormatter(self.formatter)

self.logger.addHandler(ch)if level == 'info':

self.logger.info(message)elif level == 'debug':

self.logger.debug(message)elif level == 'warning':

self.logger.warning(message)elif level == 'error':

self.logger.error(message)#這兩行代碼是為了避免日志輸出重復(fù)問題

self.logger.removeHandler(ch)

self.logger.removeHandler(fh)

fh.close()#關(guān)閉打開的文件

defdebug(self, message):

self.__console('debug', message)definfo(self, message):

self.__console('info', message)defwarning(self, message):

self.__console('warning', message)deferror(self, message):

self.__console('error', message)if __name__ == "__main__":

log=Log()

log.debug("---測試開始----")

log.info("操作步驟")

log.warning("----測試結(jié)束----")

log.error("----測試錯(cuò)誤----")

總結(jié)

以上是生活随笔為你收集整理的python日志模块备份_Python Logging模块 输出日志颜色、过期清理和日志滚动备份的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。