flask logger 使用 TimedRotatingFileHandler 报错 PermissionError 另一个程序正在使用此文件
重写 doRollover 方法:
继承 TimedRotatingFileHandler 并重写 doRollover 方法,以确保在文件重命名之前检查目标文件是否存在,如果存在,则不执行重命名操作。这可以避免多进程同时尝试重命名同一个文件的问题。
import os
import time
from logging.handlers import TimedRotatingFileHandler
class CustomTimedRotatingFileHandler(TimedRotatingFileHandler):
def doRollover(self):
if self.stream:
self.stream.close()
self.stream = None
currentTime = int(time.time())
dstNow = time.localtime(currentTime)[-1]
t = self.rolloverAt - self.interval
if self.utc:
timeTuple = time.gmtime(t)
else:
timeTuple = time.localtime(t)
dstThen = timeTuple[-1]
if dstNow != dstThen:
if dstNow:
pass
else:
pass
dfn = self.rotation_filename(self.baseFilename + ".")
if not os.path.exists(dfn):
self.rotate(self.baseFilename, dfn)
if self.backupCount > 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
self.rolloverAt = newRolloverAt