Если вы можете жить только с одним файлом резервной копии, укажите ...,backupCount=1,...
при создании экземпляра.
В противном случае вы можете создать подкласс TimedRotatingFileHandler и переопределить его getFilesToDelete
метод.
class MyRFH(TimedRotatingFileHandler):
"""
Handler for logging to a file, rotating the log file at certain timed
intervals.
If backupCount is > 0, when rollover is done, ALL previous logs are deleted.
"""
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
Will NOT keep any backup files.
Modified from Standard Library Class
"""
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))
if self.backupCount == 0:
result = []
## if len(result) < self.backupCount:
## result = []
## else:
## result.sort()
## result = result[:len(result) - self.backupCount]
return result
Адаптация примера из Ведение журнала поваренной книги
import logging, time, glob,sys,os
import logging.config
import logging.handlers
class MyRFH(logging.handlers.TimedRotatingFileHandler):
"""
Handler for logging to a file, rotating the log file at certain timed
intervals.
If backupCount is > 0, when rollover is done, ALL previous logs are deleted.
"""
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
Will NOT keep any backup files.
Modified from Standard Library Class
"""
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))
if self.backupCount == 0:
result = []
return result
if __name__ == '__main__':
LOG_FILENAME = 'logging_rotatingfile_example'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = MyRFH(LOG_FILENAME, when='s', interval=5, backupCount=1)
my_logger.addHandler(handler)
# Log some messages
for i in range(200):
my_logger.debug('i = %d' % i)
time.sleep(.1)
# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)