Skip to content

Commit cb589d1

Browse files
authored
bpo-46063: Improve algorithm for computing which rolled-over log file… (GH-30093)
1 parent eb483c4 commit cb589d1

File tree

3 files changed

+83
-5
lines changed

3 files changed

+83
-5
lines changed

Doc/library/logging.handlers.rst

+17
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,19 @@ need to override.
234234
return the same output every time for a given input, otherwise the
235235
rollover behaviour may not work as expected.
236236

237+
It's also worth noting that care should be taken when using a namer to
238+
preserve certain attributes in the filename which are used during rotation.
239+
For example, :class:`RotatingFileHandler` expects to have a set of log files
240+
whose names contain successive integers, so that rotation works as expected,
241+
and :class:`TimedRotatingFileHandler` deletes old log files (based on the
242+
``backupCount`` parameter passed to the handler's initializer) by determining
243+
the oldest files to delete. For this to happen, the filenames should be
244+
sortable using the date/time portion of the filename, and a namer needs to
245+
respect this. (If a namer is wanted that doesn't respect this scheme, it will
246+
need to be used in a subclass of :class:`TimedRotatingFileHandler` which
247+
overrides the :meth:`~TimedRotatingFileHandler.getFilesToDelete` method to
248+
fit in with the custom naming scheme.)
249+
237250
.. versionadded:: 3.3
238251

239252

@@ -443,6 +456,10 @@ timed intervals.
443456

444457
Outputs the record to the file, catering for rollover as described above.
445458

459+
.. method:: getFilesToDelete()
460+
461+
Returns a list of filenames which should be deleted as part of rollover. These
462+
are the absolute paths of the oldest backup log files written by the handler.
446463

447464
.. _socket-handler:
448465

Lib/logging/handlers.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
1+
# Copyright 2001-2021 by Vinay Sajip. All Rights Reserved.
22
#
33
# Permission to use, copy, modify, and distribute this software and its
44
# documentation for any purpose and without fee is hereby granted,
@@ -18,7 +18,7 @@
1818
Additional handlers for the logging package for Python. The core package is
1919
based on PEP 282 and comments thereto in comp.lang.python.
2020
21-
Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.
21+
Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved.
2222
2323
To use, simply 'import logging.handlers' and log away!
2424
"""
@@ -366,9 +366,22 @@ def getFilesToDelete(self):
366366
fileNames = os.listdir(dirName)
367367
result = []
368368
# See bpo-44753: Don't use the extension when computing the prefix.
369-
prefix = os.path.splitext(baseName)[0] + "."
369+
n, e = os.path.splitext(baseName)
370+
prefix = n + '.'
370371
plen = len(prefix)
371372
for fileName in fileNames:
373+
if self.namer is None:
374+
# Our files will always start with baseName
375+
if not fileName.startswith(baseName):
376+
continue
377+
else:
378+
# Our files could be just about anything after custom naming, but
379+
# likely candidates are of the form
380+
# foo.log.DATETIME_SUFFIX or foo.DATETIME_SUFFIX.log
381+
if (not fileName.startswith(baseName) and fileName.endswith(e) and
382+
len(fileName) > (plen + 1) and not fileName[plen+1].isdigit()):
383+
continue
384+
372385
if fileName[:plen] == prefix:
373386
suffix = fileName[plen:]
374387
# See bpo-45628: The date/time suffix could be anywhere in the

Lib/test/test_logging.py

+50-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2001-2019 by Vinay Sajip. All Rights Reserved.
1+
# Copyright 2001-2021 by Vinay Sajip. All Rights Reserved.
22
#
33
# Permission to use, copy, modify, and distribute this software and its
44
# documentation for any purpose and without fee is hereby granted,
@@ -16,7 +16,7 @@
1616

1717
"""Test harness for the logging module. Run all tests.
1818
19-
Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
19+
Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved.
2020
"""
2121

2222
import logging
@@ -36,6 +36,7 @@
3636
import queue
3737
import random
3838
import re
39+
import shutil
3940
import socket
4041
import struct
4142
import sys
@@ -5434,6 +5435,53 @@ def test_compute_rollover_weekly_attime(self):
54345435
finally:
54355436
rh.close()
54365437

5438+
def test_compute_files_to_delete(self):
5439+
# See bpo-46063 for background
5440+
wd = tempfile.mkdtemp(prefix='test_logging_')
5441+
self.addCleanup(shutil.rmtree, wd)
5442+
times = []
5443+
dt = datetime.datetime.now()
5444+
for i in range(10):
5445+
times.append(dt.strftime('%Y-%m-%d_%H-%M-%S'))
5446+
dt += datetime.timedelta(seconds=5)
5447+
prefixes = ('a.b', 'a.b.c', 'd.e', 'd.e.f')
5448+
files = []
5449+
rotators = []
5450+
for prefix in prefixes:
5451+
p = os.path.join(wd, '%s.log' % prefix)
5452+
rotator = logging.handlers.TimedRotatingFileHandler(p, when='s',
5453+
interval=5,
5454+
backupCount=7)
5455+
rotators.append(rotator)
5456+
if prefix.startswith('a.b'):
5457+
for t in times:
5458+
files.append('%s.log.%s' % (prefix, t))
5459+
else:
5460+
rotator.namer = lambda name: name.replace('.log', '') + '.log'
5461+
for t in times:
5462+
files.append('%s.%s.log' % (prefix, t))
5463+
# Create empty files
5464+
for fn in files:
5465+
p = os.path.join(wd, fn)
5466+
with open(p, 'wb') as f:
5467+
pass
5468+
# Now the checks that only the correct files are offered up for deletion
5469+
for i, prefix in enumerate(prefixes):
5470+
rotator = rotators[i]
5471+
candidates = rotator.getFilesToDelete()
5472+
self.assertEqual(len(candidates), 3)
5473+
if prefix.startswith('a.b'):
5474+
p = '%s.log.' % prefix
5475+
for c in candidates:
5476+
d, fn = os.path.split(c)
5477+
self.assertTrue(fn.startswith(p))
5478+
else:
5479+
for c in candidates:
5480+
d, fn = os.path.split(c)
5481+
self.assertTrue(fn.endswith('.log'))
5482+
self.assertTrue(fn.startswith(prefix + '.') and
5483+
fn[len(prefix) + 2].isdigit())
5484+
54375485

54385486
def secs(**kw):
54395487
return datetime.timedelta(**kw) // datetime.timedelta(seconds=1)

0 commit comments

Comments
 (0)