diff --git a/sentry_sdk/hub.py b/sentry_sdk/hub.py index cf8cf64537..42f0be04bd 100644 --- a/sentry_sdk/hub.py +++ b/sentry_sdk/hub.py @@ -90,7 +90,16 @@ def __enter__(self): return scope def __exit__(self, exc_type, exc_value, tb): - assert self._hub.pop_scope_unsafe() == self._layer, "popped wrong scope" + layer = self._hub.pop_scope_unsafe() + assert layer[1] == self._layer[1], "popped wrong scope" + if layer[0] != self._layer[0]: + warning = ( + "init() called inside of pushed scope. This might be entirely " + "legitimate but usually occurs when initializing the SDK inside " + "a request handler or task/job function. Try to initialize the " + "SDK as early as possible instead." + ) + logger.warning(warning) class Hub(with_metaclass(HubMeta)): diff --git a/tests/test_basics.py b/tests/test_basics.py index 8daa2a5b83..26a18f2276 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -224,3 +224,16 @@ def test_integration_scoping(): logger.warning("This is not a warning") assert len(events) == 1 + + +def test_client_initialized_within_scope(sentry_init, capture_events, caplog): + caplog.set_level(logging.WARNING) + + sentry_init(debug=True) + + with push_scope(): + sentry_init() + + record, = (x for x in caplog.records if x.levelname == "WARNING") + + assert record.msg.startswith("init() called inside of pushed scope.")