RotatingFileHandler: failed rollover drops records and deletes backups
Bug report
Test file for the report above (test_rotating_failed_rollover.py, run with python -m unittest -v test_rotating_failed_rollover). Against the stdlib handler 13 of 14 tests pass and test_backups_are_kept_while_rollover_fails fails; against the small reference handler (move the current file to a temporary name first, then shift the chain, then rename to .1, roll back on error) all 14 pass. Only the rename of the current file is made to fail, as Windows does while another process holds it. Thank you for taking a look.
"""Failed RotatingFileHandler rollover: deleted backups.
Run: python -m unittest -v test_rotating_failed_rollover
The rename of the *current* log file is made to fail with PermissionError
(what Windows does while another process holds the file open). Only the
rename of baseFilename fails; renames inside the backup chain still work.
"""
import logging
import logging.handlers
import os
import shutil
import tempfile
import unittest
from unittest import mock
N_BACKUPS = 4
class ReferenceFix(logging.handlers.RotatingFileHandler):
"""Sketch of a handler that survives a failed rollover (for comparison).
1. move the current file to a temporary name (the step that may fail; nothing else touched),
2. shift the backup chain, 3. move the temporary file to .1.
If a later step fails, everything is moved back. The stream is always reopened.
"""
def doRollover(self):
if self.stream:
self.stream.close()
self.stream = None
moved = [] # (src, dst) done so far, for rollback
tmp = self.baseFilename + ".rolling"
try:
if self.backupCount > 0:
self.rotate(self.baseFilename, tmp)
moved.append((self.baseFilename, tmp))
for i in range(self.backupCount - 1, 0, -1):
sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i))
dfn = self.rotation_filename("%s.%d" % (self.baseFilename, i + 1))
if os.path.exists(sfn):
if os.path.exists(dfn):
os.remove(dfn)
os.rename(sfn, dfn)
moved.append((sfn, dfn))
dfn = self.rotation_filename(self.baseFilename + ".1")
if os.path.exists(dfn):
os.remove(dfn)
os.rename(tmp, dfn)
except OSError:
for src, dst in reversed(moved): # roll back; the oldest file is gone anyway
try:
if os.path.exists(dst) and not os.path.exists(src):
os.rename(dst, src)
except OSError:
pass
finally:
if not self.delay:
self.stream = self._open()
class Base:
handler_class = logging.handlers.RotatingFileHandler
def setUp(self):
self.dir = tempfile.mkdtemp()
self.path = os.path.join(self.dir, "a.log")
self.h = self.handler_class(self.path, maxBytes=100, backupCount=N_BACKUPS)
self.h.setFormatter(logging.Formatter("%(message)s"))
self.log = logging.getLogger("rot-%s-%s" % (type(self).__name__, id(self)))
self.log.addHandler(self.h)
self.log.setLevel(logging.INFO)
self.log.propagate = False
self._raise = logging.raiseExceptions
logging.raiseExceptions = False # as in production: errors are only reported
self.real_rename = os.rename
def tearDown(self):
logging.raiseExceptions = self._raise
self.log.removeHandler(self.h)
self.h.close()
shutil.rmtree(self.dir, ignore_errors=True)
def _locked_rename(self, locked):
def rename(src, dst):
if locked["on"] and os.fspath(src) == self.path:
raise PermissionError(13, "simulated: file in use by another process")
return self.real_rename(src, dst)
return rename
def _fail_rename_of(self, name):
def rename(src, dst):
if os.path.basename(os.fspath(src)) == name:
raise PermissionError(13, "simulated failure of " + name)
return self.real_rename(src, dst)
return rename
def _fill_generations(self):
for g in range(1, N_BACKUPS + 2): # GEN1 .. GEN5
for i in range(3):
self.log.info("GEN%d line%d %s", g, i, "x" * 20)
def _all_text(self):
return "".join(open(os.path.join(self.dir, f)).read()
for f in sorted(os.listdir(self.dir)))
def test_control_normal_rotation_keeps_all_generations(self):
self._fill_generations()
text = self._all_text()
self.assertEqual(sorted(f for f in os.listdir(self.dir)),
["a.log"] + ["a.log.%d" % i for i in range(1, N_BACKUPS + 1)])
for g in range(1, N_BACKUPS + 2):
self.assertIn("GEN%d " % g, text)
def test_backups_are_kept_while_rollover_fails(self):
self._fill_generations()
locked = {"on": True}
with mock.patch("os.rename", self._locked_rename(locked)):
for i in range(N_BACKUPS + 2):
self.log.info("LOCKED%02d %s", i, "x" * 30)
after = self._all_text()
# every archived generation that existed must still exist
for g in range(1, N_BACKUPS + 1):
self.assertIn("GEN%d " % g, after, "GEN%d was deleted by a failed rollover" % g)
def test_rotation_resumes_after_the_lock_is_gone(self):
locked = {"on": True}
with mock.patch("os.rename", self._locked_rename(locked)):
for i in range(10):
self.log.info("LOCKED%02d %s", i, "x" * 20)
locked["on"] = False
for i in range(5):
self.log.info("AFTER%02d %s", i, "x" * 20)
self.assertEqual(self._all_text().count("AFTER"), 5)
def test_failure_in_a_chain_step_does_not_keep_deleting_backups(self):
self._fill_generations() # a.log.1=GEN4 .2=GEN3 .3=GEN2 .4=GEN1
with mock.patch("os.rename", self._fail_rename_of("a.log.2")):
for i in range(5):
self.log.info("LOCKED%02d %s", i, "x" * 30)
after = self._all_text()
for g in (2, 3, 4): # only GEN1 may be lost (it is the oldest)
self.assertIn("GEN%d " % g, after, "GEN%d was deleted" % g)
def test_backupcount_zero_is_unchanged(self):
h = logging.handlers.RotatingFileHandler(os.path.join(self.dir, "z.log"), maxBytes=50, backupCount=0)
h.setFormatter(logging.Formatter("%(message)s"))
for i in range(5):
h.handle(logging.makeLogRecord({"msg": "Z%d %s" % (i, "x" * 30), "levelno": 20}))
h.close()
self.assertEqual(open(os.path.join(self.dir, "z.log")).read().count("Z"), 5)
self.assertEqual(sorted(f for f in os.listdir(self.dir) if f.startswith("z")), ["z.log"])
class CustomNamerRotatorMixin:
def test_custom_namer_and_rotator_still_rotate(self):
p = os.path.join(self.dir, "c.log")
h = self.handler_class(p, maxBytes=60, backupCount=3)
h.namer = lambda n: n + ".bak"
def rotator(src, dst):
shutil.copyfile(src, dst)
open(src, "w").close()
h.rotator = rotator
h.setFormatter(logging.Formatter("%(message)s"))
for i in range(8):
h.handle(logging.makeLogRecord({"msg": "C%d %s" % (i, "x" * 30), "levelno": 20}))
h.close()
names = sorted(f for f in os.listdir(self.dir) if f.startswith("c.log"))
self.assertEqual(names, ["c.log", "c.log.1.bak", "c.log.2.bak", "c.log.3.bak"])
def test_delay_true_rotates(self):
p = os.path.join(self.dir, "d.log")
h = self.handler_class(p, maxBytes=60, backupCount=2, delay=True)
h.setFormatter(logging.Formatter("%(message)s"))
for i in range(6):
h.handle(logging.makeLogRecord({"msg": "D%d %s" % (i, "x" * 30), "levelno": 20}))
h.close()
self.assertTrue(os.path.exists(p + ".1") and os.path.exists(p + ".2"))
class TestStdlib(CustomNamerRotatorMixin, Base, unittest.TestCase):
pass
class TestReferenceFix(CustomNamerRotatorMixin, Base, unittest.TestCase):
handler_class = ReferenceFix
if __name__ == "__main__":
unittest.main(verbosity=2)
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Hi! I'd like to help investigate this issue.
I've reviewed the current RotatingFileHandler implementation on the main branch.
I'd like to reproduce the reported backup loss, investigate a safe solution, and add regression tests.
Is anyone currently working on this issue? Thank you!
One compatibility boundary for the temporary-file approach is the destination passed to a custom rotator. The existing custom-hook test checks the resulting filenames, but its callback ignores the destination's naming semantics.
I checked the issue's ReferenceFix alongside stdlib RotatingFileHandler on Linux / Python 3.12.14 with an existing app.log, backupCount=2, and:
handler.namer = lambda name: name + '.gz'
seen = []
def rotator(source, destination):
seen.append(Path(destination).name)
Path(source).rename(destination)
handler.rotator = rotator
handler.doRollover()
The stdlib callback receives app.log.1.gz; the reference callback receives app.log.rolling, although the final file is eventually renamed to .1.gz. A callback that selects its compressor, validates the suffix, or writes a sidecar based on destination therefore sees a different contract. Merely asserting the final filenames would miss that.
Could a regression also assert the custom rotator's source/destination arguments (and archived contents), so a fix preserves the configured destination semantics while introducing staging? This is a focused AI-assisted check of the reference sketch against Python 3.12.14; it is not a reproduction of a native Windows file lock or a test of current CPython main.