René's URL Explorer Experiment


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

direct link

Domain: github.com

IPv4 address: 140.82.114.3


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:e6efbabb-15ed-881e-6f2f-44e7269e869b
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idC146:1188C0:10469FE:159F5E2:6B064FEE
html-safe-nonce0f87eced2b58aed195ff21e14ca4a7eaf020d965e41db1676b637198bbac24fe
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDMTQ2OjExODhDMDoxMDQ2OUZFOjE1OUY1RTI6NkIwNjRGRUUiLCJ2aXNpdG9yX2lkIjoiNjY4MDQ4MzI0MzEzNTIyNTgzOCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac65b23f4cfd398181b647d17bf62e2d685b49ba8dfa59e20061e8fa6aa20b16ec
hovercard-subject-tagissue:5916629348
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/159690/issue_layout
twitter:imagehttps://opengraph.githubassets.com/20f0b0680d198d238246fb50ffacd2c39236c8bbd7e959cc93156e845583a319/python/cpython/issues/159690
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/20f0b0680d198d238246fb50ffacd2c39236c8bbd7e959cc93156e845583a319/python/cpython/issues/159690
og:image:altBug 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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamelpyu001
hostnamegithub.com
expected-hostnamegithub.com
None772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasef1f9a08f7c769a37f1dfc18ad43d463c222a7eea
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/159690#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F159690
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F159690
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/159690
Reloadhttps://github.com/python/cpython/issues/159690
Reloadhttps://github.com/python/cpython/issues/159690
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/159690
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/159690
TimedRotatingFileHandler stops rolling over permanently once doRollover() exits without updating rolloverAthttps://github.com/python/cpython/issues/159690#top
stdlibhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
type-bughttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/lpyu001
lpyu001https://github.com/lpyu001
on Oct 19, 2026https://github.com/python/cpython/issues/159690#issue-5916629348
gh-88352https://github.com/python/cpython/issues/88352
GH-116191https://github.com/python/cpython/pull/116191
gh-159690: Fix TimedRotatingFileHandler stopping rollovers after a failed or skipped rollover #159691https://github.com/python/cpython/pull/159691
gh-159690: Fix timed log rotation after a failed or duplicate rollover #159692https://github.com/python/cpython/pull/159692
[3.14] gh-159690: Fix timed log rotation after a failed or duplicate rollover (GH-159692) #160025https://github.com/python/cpython/pull/160025
[3.15] gh-159690: Fix timed log rotation after a failed or duplicate rollover (GH-159692) #160026https://github.com/python/cpython/pull/160026
lpyu001https://github.com/lpyu001
type-bughttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
on Oct 19, 2026https://github.com/python/cpython/issues/159690#event-33604478359
picnixzhttps://github.com/picnixz
stdlibhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
on Oct 19, 2026https://github.com/python/cpython/issues/159690#event-33607163447
picnixzhttps://github.com/picnixz
Logging issues 🪵https://github.com/orgs/python/projects/15
on Oct 19, 2026https://github.com/python/cpython/issues/159690#event-33607167569
vsajiphttps://github.com/vsajip
on Oct 20, 2026https://github.com/python/cpython/issues/159690#event-33756505749
gh-159690: Fix timed log rotation after a failed or duplicate rollover (https://github.com/python/cpython/commit/b12497756ba0242a2a389dd1bb6fb26ddbd48602
gh-159690https://github.com/python/cpython/issues/159690
b124977https://github.com/python/cpython/commit/b12497756ba0242a2a389dd1bb6fb26ddbd48602
[3.14] gh-159690: Fix timed log rotation after a failed or duplicate …https://github.com/python/cpython/commit/e152a82bf3bd68c5bb0831bd78901943c085e7f0
gh-159690https://github.com/python/cpython/issues/159690
e152a82https://github.com/python/cpython/commit/e152a82bf3bd68c5bb0831bd78901943c085e7f0
[3.15] gh-159690: Fix timed log rotation after a failed or duplicate …https://github.com/python/cpython/commit/1c07fb769c75740f4713e583966d96cf5d7f1006
gh-159690https://github.com/python/cpython/issues/159690
1c07fb7https://github.com/python/cpython/commit/1c07fb769c75740f4713e583966d96cf5d7f1006
vsajiphttps://github.com/vsajip
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Oct 21, 2026https://github.com/python/cpython/issues/159690#event-33817863102
github-project-automationhttps://github.com/apps/github-project-automation
Logging issues 🪵https://github.com/orgs/python/projects/15
on Oct 21, 2026https://github.com/python/cpython/issues/159690
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/159690
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/159690
stdlibhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
type-bughttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
Logging issues 🪵https://github.com/orgs/python/projects/15
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Response headers:
Servergithub.com
Content-Typetext/html; charset=utf-8
Cache-Controlmax-age=0, private, must-revalidate

Viewport: width=device-width


URLs of crawlers that visited me.