Skip to content

Commit 0e23bf2

Browse files
gaborbernatmiss-islington
authored andcommitted
gh-150818: Speed up logging.getLogger() for existing loggers (GH-150825)
(cherry picked from commit e833f57) Co-authored-by: Bernát Gábor <gaborjbernat@gmail.com>
1 parent 6825032 commit 0e23bf2

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

Lib/logging/__init__.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1370,9 +1370,16 @@ def getLogger(self, name):
13701370
logger and fix up the parent/child references which pointed to the
13711371
placeholder to now point to the logger.
13721372
"""
1373-
rv = None
13741373
if not isinstance(name, str):
13751374
raise TypeError('A logger name must be a string')
1375+
# Fast path: an already-registered, non-placeholder logger can be
1376+
# returned without taking the lock. dict.get() is atomic under both
1377+
# the GIL and free threading, and a Logger is fully initialised before
1378+
# being inserted into loggerDict under the lock, so this never sees a
1379+
# partially-constructed object.
1380+
rv = self.loggerDict.get(name)
1381+
if rv is not None and not isinstance(rv, PlaceHolder):
1382+
return rv
13761383
with _lock:
13771384
if name in self.loggerDict:
13781385
rv = self.loggerDict[name]
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Speed up :func:`logging.getLogger` with a lock-free fast path that returns an
2+
already-registered logger without acquiring the logging lock. Patch by Bernát
3+
Gábor.

0 commit comments

Comments
 (0)