Title: logging reopens file with same mode, possibly truncating
Type: behavior Stage: patch review
Components: Library (Lib) Versions: Python 3.8
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: andrei.avk, ecatmur2, miss-islington
Priority: normal Keywords: patch

Created on 2020-11-16 19:48 by ecatmur2, last changed 2021-07-25 20:17 by miss-islington.

Pull Requests
URL Status Linked Edit
PR 27310 merged andrei.avk, 2021-07-23 16:37
Messages (3)
msg381146 - (view) Author: Ed Catmur (ecatmur2) Date: 2020-11-16 19:48
If a logging.FileHandler is configured with mode='w', or if logging.basicConfig is called with filemode='w' (as suggested by the Basic Logging Tutorial
and if some code logs during shutdown, after logging has closed its handlers (asyncio is prone to do this, e.g.),
then logging.FileHandler._open will reopen the log file with the same mode as it was originally opened with, potentially truncating it and losing valuable information:

import atexit
atexit.register(lambda:"so long"))
import logging
logging.basicConfig(filename='test.log', filemode='w', level=logging.INFO)"super important stuff")

$ python
$ cat test.log
INFO:root:so long

I have a hunch that the fix to issue 26789 will potentially make things worse, as previously at least there was a chance that logging had been fully unloaded so that the call to open would fail.
msg398078 - (view) Author: Andrei Kulakov (andrei.avk) * (Python triager) Date: 2021-07-23 16:38
I've put up a PR here:

If this looks good, I will update the docs and add news entry.
msg398195 - (view) Author: miss-islington (miss-islington) Date: 2021-07-25 20:17
New changeset 96cf5a63d2dbadaebf236362b4c7c09c51fda55c by andrei kulakov in branch 'main':
bpo-42378: fixed log truncation on logging shutdown (GH-27310)
Date User Action Args
2021-07-25 20:17:50miss-islingtonsetnosy: + miss-islington
messages: + msg398195
2021-07-23 16:38:46andrei.avksetmessages: + msg398078
2021-07-23 16:37:40andrei.avksetkeywords: + patch
nosy: + andrei.avk

pull_requests: + pull_request25855
stage: patch review
2020-11-16 19:48:22ecatmur2create