From 22af06209b0412f60bb75565f80f098d846cc3bb Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Thu, 23 Jul 2026 09:54:36 +0300 Subject: [PATCH] gh-79366: Fix a race condition when removing a logging handler removeHandler() mutated the handler list in place, so if a handler was removed while callHandlers() was iterating the same list, the following handlers could be skipped. Replace the list instead of mutating it. Co-Authored-By: Ben Spiller <11992588+ben-spiller@users.noreply.github.com> Co-Authored-By: Claude Opus 4.8 (1M context) --- Lib/logging/__init__.py | 6 +++++- Lib/test/test_logging.py | 17 +++++++++++++++++ ...026-07-23-06-53-01.gh-issue-79366.3gMT7I.rst | 3 +++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-07-23-06-53-01.gh-issue-79366.3gMT7I.rst diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index b4a5f5cc2f598f5..53becca4e3a6969 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -1709,7 +1709,11 @@ def removeHandler(self, hdlr): """ with _lock: if hdlr in self.handlers: - self.handlers.remove(hdlr) + # Replace the list instead of mutating it in place, so that + # callHandlers() can iterate it without a lock (gh-79366). + handlers = self.handlers.copy() + handlers.remove(hdlr) + self.handlers = handlers def hasHandlers(self): """ diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index 06b3aa66fc47a31..2bb36db9bbd3bc8 100644 --- a/Lib/test/test_logging.py +++ b/Lib/test/test_logging.py @@ -814,6 +814,23 @@ def lock_holder_thread_fn(): support.wait_process(pid, exitcode=0) + def test_remove_handler_while_emitting(self): + # Removing a handler while callHandlers() iterates over the handlers + # should not cause the following handlers to be skipped (gh-79366). + logger = logging.Logger('test_remove_handler_while_emitting') + calls = [] + class RemovingHandler(logging.Handler): + def emit(self, record): + calls.append('removing') + logger.removeHandler(self) + class CountingHandler(logging.Handler): + def emit(self, record): + calls.append('counting') + logger.addHandler(RemovingHandler()) + logger.addHandler(CountingHandler()) + logger.error('spam') + self.assertEqual(calls, ['removing', 'counting']) + class BadStream(object): def write(self, data): diff --git a/Misc/NEWS.d/next/Library/2026-07-23-06-53-01.gh-issue-79366.3gMT7I.rst b/Misc/NEWS.d/next/Library/2026-07-23-06-53-01.gh-issue-79366.3gMT7I.rst new file mode 100644 index 000000000000000..ecb3c3ad92cb2be --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-23-06-53-01.gh-issue-79366.3gMT7I.rst @@ -0,0 +1,3 @@ +Fixed a race condition in :mod:`logging`: +if a handler was removed while a record was being emitted, +the following handlers of the same logger could be skipped.