Skip to content

gh-109653: Improve import time of logging by lazy loading traceback #112995

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion Lib/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Reduce the import time of :mod:`logging` module by ~15%. Patch by Daniel Hollas.