国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python logging 日志輪轉文件不刪除問題的解決方法

2019-11-25 16:37:35
字體:
來源:轉載
供稿:網友

前言

最近在維護項目的python項目代碼,項目使用了 python 的日志模塊 logging, 設定了保存的日志數目, 不過沒有生效,還要通過contab定時清理數據。

分析

項目使用了 logging 的 TimedRotatingFileHandler :

#!/user/bin/env python# -*- coding: utf-8 -*-import loggingfrom logging.handlers import TimedRotatingFileHandlerlog = logging.getLogger()file_name = "./test.log"logformatter = logging.Formatter('%(asctime)s [%(levelname)s]|%(message)s')loghandle = TimedRotatingFileHandler(file_name, 'midnight', 1, 2)loghandle.setFormatter(logformatter)loghandle.suffix = '%Y%m%d'log.addHandler(loghandle)log.setLevel(logging.DEBUG)log.debug("init successful")

參考 python logging 的官方文檔:

https://docs.python.org/2/library/logging.html

查看其 入門 實例,可以看到使用按時間輪轉的相關內容:

import logging# create loggerlogger = logging.getLogger('simple_example')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.debug('debug message')

粗看下,也看不出有什么不對的地方。

那就看下logging的代碼,找到TimedRotatingFileHandler 相關的內容,其中刪除過期日志的內容:

logging/handlers.py

def getFilesToDelete(self):  """  Determine the files to delete when rolling over.  More specific than the earlier method, which just used glob.glob().  """  dirName, baseName = os.path.split(self.baseFilename)  fileNames = os.listdir(dirName)  result = []  prefix = baseName + "."  plen = len(prefix)  for fileName in fileNames:   if fileName[:plen] == prefix:    suffix = fileName[plen:]    if self.extMatch.match(suffix):     result.append(os.path.join(dirName, fileName))  result.sort()  if len(result) < self.backupCount:   result = []  else:   result = result[:len(result) - self.backupCount]  return result

輪轉刪除的原理,是查找到日志目錄下,匹配suffix后綴的文件,加入到刪除列表,如果超過了指定的數目就加入到要刪除的列表中,再看下匹配的原理:

elif self.when == 'D' or self.when == 'MIDNIGHT':   self.interval = 60 * 60 * 24 # one day   self.suffix = "%Y-%m-%d"   self.extMatch = r"^/d{4}-/d{2}-/d{2}$"

exMatch 是一個正則的匹配,格式是 - 分隔的時間,而我們自己設置了新的suffix沒有 - 分隔:

loghandle.suffix = '%Y%m%d'
這樣就找不到要刪除的文件,不會刪除相關的日志。

總結

1. 封裝好的庫,盡量使用公開的接口,不要隨便修改內部變量;

2. 代碼有問題地,實在找不到原因,可以看下代碼。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安陆市| 玛纳斯县| 万山特区| 岱山县| 陕西省| 沂南县| 鸡泽县| 天台县| 云霄县| 金塔县| 新营市| 屯门区| 定边县| 独山县| 监利县| 西盟| 科技| 漳州市| 甘泉县| 曲松县| 阿图什市| 宣汉县| 三河市| 江永县| 安龙县| 嘉定区| 临清市| 驻马店市| 临汾市| 宣武区| 新闻| 惠来县| 莱西市| 二连浩特市| 长寿区| 肥西县| 郓城县| 岱山县| 柳林县| 抚顺市| 治多县|