Title: `TimedRotatingFileHandler` stops rolling over permanently once `doRollover()` exits without updating `rolloverAt` · Issue #159690 · python/cpython · GitHub
Open Graph Title: `TimedRotatingFileHandler` stops rolling over permanently once `doRollover()` exits without updating `rolloverAt` · Issue #159690 · python/cpython
X Title: `TimedRotatingFileHandler` stops rolling over permanently once `doRollover()` exits without updating `rolloverAt` · Issue #159690 · python/cpython
Description: Bug report Summary TimedRotatingFileHandler.doRollover() updates rolloverAt only on its last line. If it exits earlier, rolloverAt stays in the past. It can exit earlier by raising after the base file has been renamed, or by taking the #...
Open Graph Description: Bug report Summary TimedRotatingFileHandler.doRollover() updates rolloverAt only on its last line. If it exits earlier, rolloverAt stays in the past. It can exit earlier by raising after the base f...
X Description: Bug report Summary TimedRotatingFileHandler.doRollover() updates rolloverAt only on its last line. If it exits earlier, rolloverAt stays in the past. It can exit earlier by raising after the base f...
Opengraph URL: https://github.com/python/cpython/issues/159690
X: @github
Domain: github.com
IPv4 address: 140.82.114.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`TimedRotatingFileHandler` stops rolling over permanently once `doRollover()` exits without updating `rolloverAt`","articleBody":"### Bug report\n\n### Summary\n\n`TimedRotatingFileHandler.doRollover()` updates `rolloverAt` only on its last line. If it exits earlier, `rolloverAt` stays in the past. It can exit earlier by raising after the base file has been renamed, or by taking the `# Already rolled over.` early return. The early return is taken without any error by a handler using local time at DST changes: with hourly rollover, and with the default daily rollover (`when='midnight'`) when nothing is logged between midnight and the end of DST. From then on, every `emit()` calls `doRollover()` again and computes the same backup name. That name exists on disk, so the early return is taken again. The handler never rolls over again, the base file grows without bound, `backupCount` cleanup stops, and nothing is reported beyond the first error, if there was one.\n\n### Reproduction Code\n\nA single `FileNotFoundError` from `os.remove()` during backup cleanup is enough. This happens when an old backup is removed by another process between `os.listdir()` and `os.remove()`. The failure is injected with `unittest.mock`, and the clock is mocked so that no sleeping is needed:\n\n```python\nimport logging, logging.handlers, os, tempfile, time\nfrom unittest import mock\n\nd = tempfile.mkdtemp()\nfn = os.path.join(d, \"app.log\")\nh = logging.handlers.TimedRotatingFileHandler(fn, when=\"S\", backupCount=1)\nnow = [time.time()]\nlog = lambda msg: h.emit(logging.makeLogRecord({\"msg\": msg}))\n\nreal_remove = os.remove\ndef remove_once(path):\n # Simulate an old backup removed by someone else between\n # os.listdir() and os.remove().\n os.remove = real_remove\n real_remove(path)\n raise FileNotFoundError(path)\n\nwith mock.patch(\"time.time\", lambda: now[0]):\n for i in range(3):\n now[0] += 2; log(f\"a{i}\") # normal rollovers\n os.remove = remove_once\n now[0] += 2; log(\"b\") # rollover whose cleanup fails once\n os.remove = real_remove\n for i in range(5):\n now[0] += 2; log(f\"c{i}\") # five more rollover periods\n print(\"rolloverAt in the past:\", h.rolloverAt \u003c now[0])\nh.close()\nprint(sorted(os.listdir(d)))\nwith open(fn) as f:\n print(\"app.log:\", f.read().split())\n```\n\nThe script gives the results below on the main branch and on 3.12.3.\n\n### Actual Behavior\n\nThe failed rollover is reported once through `handleError()`, and after that nothing more is reported:\n\n```\n--- Logging error ---\nTraceback (most recent call last):\nFileNotFoundError: /tmp/tmpup6vttee/app.log.2026-10-18_21-18-38\nCall stack:\nMessage: 'b'\nArguments: ()\nrolloverAt in the past: True\n['app.log', 'app.log.2026-10-18_21-18-40']\napp.log: ['c0', 'c1', 'c2', 'c3', 'c4']\n```\n\nFive more rollover periods pass with no rollover. All of their records are written to `app.log`, and no new backup is created. The record that triggered the failed rollover (`b`) is not written to any file.\n\n### Expected Behavior\n\nA failure during one rollover, or a backup that already exists, should affect only that rollover. The next period boundary should trigger a normal rollover: the base file should then hold only the current period's records, and old backups should be pruned according to `backupCount`. `RotatingFileHandler` behaves this way after the same kind of failure: its next `emit()` reopens the file and rotates normally.\n\n### Analysis\n\nThe relevant part of `TimedRotatingFileHandler.doRollover()` in `Lib/logging/handlers.py`:\n\n```python\n dfn = self.rotation_filename(self.baseFilename + \".\" +\n time.strftime(self.suffix, timeTuple))\n if os.path.exists(dfn):\n # Already rolled over.\n return\n\n if self.stream:\n self.stream.close()\n self.stream = None\n self.rotate(self.baseFilename, dfn)\n if self.backupCount > 0:\n for s in self.getFilesToDelete():\n os.remove(s)\n if not self.delay:\n self.stream = self._open()\n self.rolloverAt = self.computeRollover(currentTime)\n```\n\n`dfn` is derived from `t = self.rolloverAt - self.interval`. If `os.remove()`, `_open()` or a user-supplied `rotator` raises after `self.rotate()` has created `dfn`, the final assignment is skipped. `BaseRotatingHandler.emit()` catches the exception and calls `handleError()`. On every later `emit()`, `shouldRollover()` returns true because `time.time() >= self.rolloverAt`. `doRollover()` then computes the same `dfn`, finds it on disk, and returns early, which also leaves `rolloverAt` unchanged. `FileHandler.emit()` reopens `baseFilename` because `self.stream` is `None`, so records keep going to the base file without any rollover. Each record also pays for an extra `os.path.exists()` call.\n\nA one-time `_open()` failure has the same effect. With `mock.patch.object(h, \"_open\", side_effect=OSError(\"injected\"))` around a single rolling-over `emit()`, followed by three more periods, the result on main and on 3.12.3 is:\n\n```\nOSError: injected\nrolloverAt in the past: True\napp.log ['c0', 'c1', 'c2']\napp.log.2026-10-18_21-18-35 ['a']\n```\n\nThe early return was added in gh-88352 (GH-116191), which replaced the previous `os.remove(dfn)` with `return` so that existing backups are not overwritten. The same code is on the 3.13 and 3.14 branches. With 3.10, where `os.remove(dfn)` is still used, the script keeps rolling over (`rolloverAt in the past: False`, `app.log: ['c4']`).\n\nThe early return is also reached by a single handler with `when='H'` and local time (`utc=False`) at DST changes, with no exception involved. With a mocked clock in `America/New_York`, the handler stopped rolling over at both the March and the November change. For the November change (Unix only, uses `time.tzset()`):\n\n```python\nimport logging, logging.handlers, os, tempfile, time\nfrom unittest import mock\n\nos.environ[\"TZ\"] = \"America/New_York\" # DST ends 2026-11-01 02:00\ntime.tzset()\n\nd = tempfile.mkdtemp()\nfn = os.path.join(d, \"app.log\")\nstart = time.mktime((2026, 10, 31, 23, 0, 0, 0, 0, -1))\nnow = [start]\nwith mock.patch(\"time.time\", lambda: now[0]):\n h = logging.handlers.TimedRotatingFileHandler(fn, when=\"H\", delay=True)\n for i in range(6):\n now[0] = start + i * 3600\n msg = time.strftime(\"%H:%M%Z\", time.localtime(now[0]))\n h.emit(logging.makeLogRecord({\"msg\": msg}))\nh.close()\nfor name in sorted(os.listdir(d)):\n with open(os.path.join(d, name)) as f:\n print(name, f.read().split())\n```\n\nOn main and on 3.12.3, the rollover at 01:00 EST finds that its backup name already exists. No rollover happens after that, and the records of four hourly intervals stay in `app.log`:\n\n```\napp.log ['01:00EDT', '01:00EST', '02:00EST', '03:00EST']\napp.log.2026-10-31_23 ['23:00EDT']\napp.log.2026-11-01_00 ['00:00EDT']\n```\n\nDaily rollover at midnight is affected when the first record after midnight on the day DST ends is logged after the change. In `America/New_York` that is after 02:00 EDT, and in `Europe/Berlin` after 03:00 CEST. A handler that also gets a record between midnight and the change keeps rolling over. With records at 09:00 and 18:00 each day:\n\n```python\nimport logging, logging.handlers, os, tempfile, time\nfrom unittest import mock\n\nos.environ[\"TZ\"] = \"America/New_York\" # DST ends 2026-11-01 02:00\ntime.tzset()\n\nd = tempfile.mkdtemp()\nfn = os.path.join(d, \"app.log\")\nts = lambda *args: time.mktime(args + (0, 0, -1))\nnow = [ts(2026, 10, 30, 8, 0, 0)]\nwith mock.patch(\"time.time\", lambda: now[0]):\n h = logging.handlers.TimedRotatingFileHandler(fn, when=\"midnight\", delay=True)\n # No records between midnight and 09:00.\n for day in [(2026, 10, 30), (2026, 10, 31), (2026, 11, 1),\n (2026, 11, 2), (2026, 11, 3)]:\n for hour in (9, 18):\n now[0] = ts(*day, hour, 0, 0)\n msg = time.strftime(\"%m-%d_%H:%M%Z\", time.localtime(now[0]))\n h.emit(logging.makeLogRecord({\"msg\": msg}))\nh.close()\nfor name in sorted(os.listdir(d)):\n with open(os.path.join(d, name)) as f:\n print(name, f.read().split())\n```\n\nOn main and on 3.12.3, the rollover on November 1 finds that its backup name already exists. No rollover happens after that, and the records of four days stay in `app.log`:\n\n```\napp.log ['10-31_09:00EDT', '10-31_18:00EDT', '11-01_09:00EST', '11-01_18:00EST', '11-02_09:00EST', '11-02_18:00EST', '11-03_09:00EST', '11-03_18:00EST']\napp.log.2026-10-30 ['10-30_09:00EDT', '10-30_18:00EDT']\n```\n\nThe same happened in `Europe/Berlin` at the October change. The start of DST in March did not stop the daily handler in either time zone.\n\n\n\n### CPython versions tested on:\n\nCPython main branch, 3.12\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-159691\n* gh-159692\n* gh-160025\n* gh-160026\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/lpyu001","@type":"Person","name":"lpyu001"},"datePublished":"2026-10-19T02:14:00Z","url":"https://github.com/python/cpython/issues/159690"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:e6efbabb-15ed-881e-6f2f-44e7269e869b |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | C146:1188C0:10469FE:159F5E2:6B064FEE |
| html-safe-nonce | 0f87eced2b58aed195ff21e14ca4a7eaf020d965e41db1676b637198bbac24fe |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDMTQ2OjExODhDMDoxMDQ2OUZFOjE1OUY1RTI6NkIwNjRGRUUiLCJ2aXNpdG9yX2lkIjoiNjY4MDQ4MzI0MzEzNTIyNTgzOCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 65b23f4cfd398181b647d17bf62e2d685b49ba8dfa59e20061e8fa6aa20b16ec |
| hovercard-subject-tag | issue:5916629348 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/159690/issue_layout |
| twitter:image | https://opengraph.githubassets.com/20f0b0680d198d238246fb50ffacd2c39236c8bbd7e959cc93156e845583a319/python/cpython/issues/159690 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/20f0b0680d198d238246fb50ffacd2c39236c8bbd7e959cc93156e845583a319/python/cpython/issues/159690 |
| og:image:alt | Bug report Summary TimedRotatingFileHandler.doRollover() updates rolloverAt only on its last line. If it exits earlier, rolloverAt stays in the past. It can exit earlier by raising after the base f... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | lpyu001 |
| hostname | github.com |
| expected-hostname | github.com |
| None | 772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | f1f9a08f7c769a37f1dfc18ad43d463c222a7eea |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width