diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index eb7e020d1edfc0..d8cfe9400012f4 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -23,7 +23,10 @@ To use, simply 'import logging' and log away! """ -import sys, os, time, io, re, traceback, warnings, weakref, collections.abc +import sys, os, time, io, re, warnings, weakref, collections.abc + +# Speed up import time by delaying traceback import until needed +traceback = None from types import GenericAlias from string import Template @@ -653,6 +656,9 @@ def formatException(self, ei): This default implementation just uses traceback.print_exception() """ + global traceback + if traceback is None: + import traceback sio = io.StringIO() tb = ei[2] # See issues #9427, #1553375. Commented out for now. @@ -1061,6 +1067,9 @@ def handleError(self, record): The record which was being processed is passed in to this method. """ if raiseExceptions and sys.stderr: # see issue 13807 + global traceback + if traceback is None: + import traceback exc = sys.exception() try: sys.stderr.write('--- Logging error ---\n') @@ -1601,6 +1610,9 @@ def findCaller(self, stack_info=False, stacklevel=1): co = f.f_code sinfo = None if stack_info: + global traceback + if traceback is None: + import traceback with io.StringIO() as sio: sio.write("Stack (most recent call last):\n") traceback.print_stack(f, file=sio) diff --git a/Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst b/Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst new file mode 100644 index 00000000000000..847f03f9048220 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst @@ -0,0 +1 @@ +Reduce the import time of :mod:`logging` module by ~15%. Patch by Daniel Hollas.