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.