From 641a2bb08095732074b1dcfdad6767ffa699988a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Thu, 4 Jun 2026 09:15:12 -0700 Subject: [PATCH] gh-150818: Speed up logging.getLogger() for existing loggers (GH-150825) (cherry picked from commit e833f57383546a02d61028aa87194aa65d5a92a3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bernát Gábor --- Lib/logging/__init__.py | 9 ++++++++- .../2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst | 3 +++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index 6eef90ae5cd9143..9febc50b1264ef4 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -1373,9 +1373,16 @@ def getLogger(self, name): logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. """ - rv = None if not isinstance(name, str): raise TypeError('A logger name must be a string') + # Fast path: an already-registered, non-placeholder logger can be + # returned without taking the lock. dict.get() is atomic under both + # the GIL and free threading, and a Logger is fully initialised before + # being inserted into loggerDict under the lock, so this never sees a + # partially-constructed object. + rv = self.loggerDict.get(name) + if rv is not None and not isinstance(rv, PlaceHolder): + return rv with _lock: if name in self.loggerDict: rv = self.loggerDict[name] diff --git a/Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst b/Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst new file mode 100644 index 000000000000000..3bb16001cc0bb41 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-02-15-44-58.gh-issue-150818.Orcefu.rst @@ -0,0 +1,3 @@ +Speed up :func:`logging.getLogger` with a lock-free fast path that returns an +already-registered logger without acquiring the logging lock. Patch by Bernát +Gábor.