作者:viggieg-may_789 | 来源:互联网 | 2023-05-25 20:03
Python 2.7:每次日志遇到翻转事件(使用RotatingFileHandler记录日志)时,都会生成"备份"日志.
例如 :
logFile = 'general.log'
file_handler = logging.handlers.TimedRotatingFileHandler(logFile,when="midnight")
午夜翻转和翻转事件的结果创建了以下文件:
general.log.2015-01-21
此模块是否为这些文件名的结构提供了任何灵活性?即使用不同的约定......20150121_general.log
1> Michele d'Am..:
简短的回答是否定的:根据TimedRotatingFileHandler文档,您无法做到这一点.
基于when
参数的后缀更改,如代码https://hg.python.org/cpython/file/2.7/Lib/logging/handlers.py#l187中所示
从相同的源代码中您可以看到覆盖suffix
很简单,但您也必须覆盖extMatch
:
class MyTimedRotatingFileHandler(TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
super(MyTimedRotatingFileHandler,self).__init__(*args,**kwargs)
self.suffix = "%Y%m%d"
self.extMatch = re.compile(r"^\d{4}\d{2}\d{2}$")
不幸的是更换点分离器和交换suffix
,并basename
没有那么简单,你必须重写doRollover()
和getFilesToDelete()
方法.
黑客可以是这样的(未经测试)...我希望它有效,但我不能给任何逮捕:)
class MyTimedRotatingFileHandler(TimedRotatingFileHandler):
self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
def getFilesToDelete(self):
""" CUT, PASTE AND .... HACK
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
extMatch = re.compile(r"^\d{4}\d{2}\d{2}$")
ends = "_" + baseName + ".log"
elen = len(ends)
for fileName in fileNames:
if fileName[-elen:] == ends:
date = fileName[-elen:]
if self.extMatch.match(date):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) 0:
for s in self.getFilesToDelete():
os.remove(s)
if not self.delay:
self.stream = self._open()
newRolloverAt = self.computeRollover(currentTime)
while newRolloverAt <= currentTime:
newRolloverAt = newRolloverAt + self.interval
#If DST changes and midnight or weekly rollover, adjust for this.
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
self.rolloverAt = newRolloverAt