Skip to content

Commit f25e4f5

Browse files
committed
fix(spotlight): More defensive Django spotlight middleware injection
Turns out `settings.MIDDLEWARE` does not have to be a `list`. This causes issues as not all iterables support appending items to them. This PR leverages `itertools.chain` along with `type(settings.MIDDLEWARE)` to extend the middleware list while keeping its original type. It also adds a try-except block around the injection code to make sure it doesn't block anything further down in the unexpected case that it fails.
1 parent f493057 commit f25e4f5

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

sentry_sdk/spotlight.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import urllib.error
66
import urllib3
77

8+
from itertools import chain
9+
810
from typing import TYPE_CHECKING
911

1012
if TYPE_CHECKING:
@@ -18,6 +20,7 @@
1820

1921

2022
DEFAULT_SPOTLIGHT_URL = "http://localhost:8969/stream"
23+
DJANGO_SPOTLIGHT_MIDDLEWARE_PATH = "sentry_sdk.spotlight.SpotlightMiddleware"
2124

2225

2326
class SpotlightClient:
@@ -112,9 +115,18 @@ def setup_spotlight(options):
112115
else:
113116
return None
114117

115-
if settings is not None and env_to_bool(
116-
os.environ.get("SENTRY_SPOTLIGHT_ON_ERROR", "1")
118+
if (
119+
settings is not None
120+
and settings.DEBUG
121+
and env_to_bool(os.environ.get("SENTRY_SPOTLIGHT_ON_ERROR", "1"))
117122
):
118-
settings.MIDDLEWARE.append("sentry_sdk.spotlight.SpotlightMiddleware")
123+
try:
124+
middleware = settings.MIDDLEWARE
125+
if DJANGO_SPOTLIGHT_MIDDLEWARE_PATH not in middleware:
126+
settings.MIDDLEWARE = type(middleware)(
127+
chain(middleware, (DJANGO_SPOTLIGHT_MIDDLEWARE_PATH,))
128+
)
129+
except Exception as err:
130+
logger.error("Cannot inject Spotlight middleware", exc_info=err)
119131

120132
return SpotlightClient(url)

0 commit comments

Comments
 (0)