Skip to content

Commit 3fd09e5

Browse files
feat(tracing): Warn when transaction entered without calling start_transaction
Users who enter a transaction without calling `start_transaction` likely intended to start the transaction, since without a call to `start_transaction`, their transaction will not get sent to Sentry. This warning message clarifies this behavior, and could help avoid the confusion that led to issue #2990. Also, add tests to ensure the message is logged.
1 parent 7674bf2 commit 3fd09e5

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

sentry_sdk/tracing.py

+19
Original file line numberDiff line numberDiff line change
@@ -714,8 +714,27 @@ def __repr__(self):
714714
)
715715
)
716716

717+
def _possibly_started(self):
718+
# type: () -> bool
719+
"""Returns whether the transaction might have been started.
720+
721+
If this returns False, we know that the transaction was not started
722+
with sentry_sdk.start_transaction, and therefore the transaction will
723+
be discarded.
724+
"""
725+
726+
# We must explicitly check self.sampled is False since self.sampled can be None
727+
return self._span_recorder is not None or self.sampled is False
728+
717729
def __enter__(self):
718730
# type: () -> Transaction
731+
if not self._possibly_started():
732+
logger.warning(
733+
"Transaction was entered without being started with sentry_sdk.start_transaction."
734+
"The transaction will not be sent to Sentry. To fix, start the transaction by"
735+
"passing it to sentry_sdk.start_transaction."
736+
)
737+
719738
super().__enter__()
720739

721740
if self._profile is not None:

tests/tracing/test_misc.py

+16
Original file line numberDiff line numberDiff line change
@@ -401,3 +401,19 @@ def test_transaction_dropeed_sampled_false(sentry_init):
401401
mock_logger.debug.assert_any_call(
402402
"Discarding transaction because it was not started with sentry_sdk.start_transaction"
403403
)
404+
405+
406+
def test_transaction_not_started_warning(sentry_init):
407+
sentry_init(enable_tracing=True)
408+
409+
tx = Transaction()
410+
411+
with mock.patch("sentry_sdk.tracing.logger") as mock_logger:
412+
with tx:
413+
pass
414+
415+
mock_logger.warning.assert_any_call(
416+
"Transaction was entered without being started with sentry_sdk.start_transaction."
417+
"The transaction will not be sent to Sentry. To fix, start the transaction by"
418+
"passing it to sentry_sdk.start_transaction."
419+
)

0 commit comments

Comments
 (0)