Skip to content

Commit 646cbf6

Browse files
[3.15] gh-160433: Correct timed log backup names across DST changes (GH-160564) (#160578)
Co-authored-by: Liang Hu <35699841+LarryHu0217@users.noreply.github.com>
1 parent 8e53ea2 commit 646cbf6

3 files changed

Lines changed: 84 additions & 8 deletions

File tree

‎Lib/logging/handlers.py‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -436,14 +436,17 @@ def doRollover(self):
436436
timeTuple = time.gmtime(t)
437437
else:
438438
timeTuple = time.localtime(t)
439-
dstNow = time.localtime(currentTime)[-1]
440-
dstThen = timeTuple[-1]
441-
if dstNow != dstThen:
442-
if dstNow:
443-
addend = 3600
444-
else:
445-
addend = -3600
446-
timeTuple = time.localtime(t + addend)
439+
# DST affects calendar-based intervals, not fixed-duration ones.
440+
if self.when == 'MIDNIGHT' or self.when.startswith('W'):
441+
# A record can arrive well after the scheduled rollover.
442+
dstAtRollover = time.localtime(self.rolloverAt)[-1]
443+
dstThen = timeTuple[-1]
444+
if dstAtRollover != dstThen:
445+
if dstAtRollover:
446+
addend = 3600
447+
else:
448+
addend = -3600
449+
timeTuple = time.localtime(t + addend)
447450
dfn = self.rotation_filename(self.baseFilename + "." +
448451
time.strftime(self.suffix, timeTuple))
449452
self.rolloverAt = self.computeRollover(currentTime)

‎Lib/test/test_logging.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6638,6 +6638,77 @@ def rotator(source, dest):
66386638
rh.close()
66396639

66406640
class TimedRotatingFileHandlerTest(BaseFileTest):
6641+
def assert_rollover_contents(self, when, timestamps, expected, **kwargs):
6642+
with tempfile.TemporaryDirectory() as dirname:
6643+
filename = os.path.join(dirname, 'app.log')
6644+
now = [timestamps[0]]
6645+
with patch('time.time', lambda: now[0]):
6646+
handler = logging.handlers.TimedRotatingFileHandler(
6647+
filename, when=when, delay=True, encoding='utf-8', **kwargs)
6648+
try:
6649+
for i, timestamp in enumerate(timestamps):
6650+
now[0] = timestamp
6651+
handler.emit(logging.makeLogRecord({'msg': str(i)}))
6652+
finally:
6653+
handler.close()
6654+
actual = {}
6655+
for name in os.listdir(dirname):
6656+
with open(os.path.join(dirname, name), encoding='utf-8') as f:
6657+
actual[name.removeprefix('app.log')] = f.read().splitlines()
6658+
self.assertEqual(actual, expected)
6659+
6660+
@support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
6661+
def test_rollover_fixed_interval_dst(self):
6662+
DT = datetime.datetime
6663+
cases = (
6664+
('H', DT(2026, 3, 8, 1, 30), 3),
6665+
('H', DT(2026, 11, 1, 1, 30), 2),
6666+
('D', DT(2026, 3, 7, 23, 30), 3),
6667+
('D', DT(2026, 11, 1, 0, 30), 2),
6668+
)
6669+
for when, start, count in cases:
6670+
interval = 3600 if when == 'H' else 86400
6671+
timestamps = [start.timestamp() + i * interval for i in range(count)]
6672+
suffix = '.%Y-%m-%d_%H' if when == 'H' else '.%Y-%m-%d'
6673+
for utc in (False, True):
6674+
with self.subTest(when=when, start=start, utc=utc):
6675+
convert = time.gmtime if utc else time.localtime
6676+
expected = {
6677+
time.strftime(suffix, convert(timestamp)): [str(i)]
6678+
for i, timestamp in enumerate(timestamps[:-1])
6679+
}
6680+
expected[''] = [str(count - 1)]
6681+
self.assert_rollover_contents(
6682+
when, timestamps, expected, utc=utc)
6683+
6684+
@support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
6685+
def test_rollover_delayed_dst(self):
6686+
DT = datetime.datetime
6687+
cases = (
6688+
('MIDNIGHT', None,
6689+
[DT(2026, 10, day, hour).timestamp()
6690+
for day in (30, 31) for hour in (9, 18)] +
6691+
[DT(2026, 11, day, hour).timestamp()
6692+
for day in (1, 2, 3) for hour in (9, 18)],
6693+
{'.2026-10-30': ['0', '1'], '.2026-10-31': ['2', '3'],
6694+
'.2026-11-01': ['4', '5'], '.2026-11-02': ['6', '7'],
6695+
'': ['8', '9']}),
6696+
('W6', None,
6697+
[DT(2026, 10, 23, 9).timestamp(),
6698+
DT(2026, 11, 1, 9).timestamp(),
6699+
DT(2026, 11, 2, 9).timestamp()],
6700+
{'.2026-10-19': ['0'], '.2026-10-26': ['1'], '': ['2']}),
6701+
('MIDNIGHT', datetime.time(23, 30),
6702+
[DT(2026, month, 1, 12).timestamp() for month in (3, 4, 10, 12)],
6703+
{'.2026-02-28': ['0'], '.2026-03-31': ['1'],
6704+
'.2026-09-30': ['2'], '': ['3']}),
6705+
)
6706+
for when, at_time, timestamps, expected in cases:
6707+
for utc in (False, True):
6708+
with self.subTest(when=when, atTime=at_time, utc=utc):
6709+
self.assert_rollover_contents(
6710+
when, timestamps, expected, atTime=at_time, utc=utc)
6711+
66416712
@unittest.skipIf(support.is_wasi, "WASI does not have /dev/null.")
66426713
def test_should_not_rollover(self):
66436714
# See bpo-45401. Should only ever rollover regular files
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix incorrect backup names around daylight saving time changes in
2+
:class:`logging.handlers.TimedRotatingFileHandler`, including delayed rollovers.

0 commit comments

Comments
 (0)