Skip to content

Commit

Permalink
feat(tracing): Warn if not-started transaction entered (#3003)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
szokeasaurusrex committed Jun 6, 2024
1 parent 7674bf2 commit c2af1b0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
19 changes: 19 additions & 0 deletions sentry_sdk/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,8 +714,27 @@ def __repr__(self):
)
)

def _possibly_started(self):
# type: () -> bool
"""Returns whether the transaction might have been started.
If this returns False, we know that the transaction was not started
with sentry_sdk.start_transaction, and therefore the transaction will
be discarded.
"""

# We must explicitly check self.sampled is False since self.sampled can be None
return self._span_recorder is not None or self.sampled is False

def __enter__(self):
# type: () -> Transaction
if not self._possibly_started():
logger.warning(
"Transaction was entered without being started with sentry_sdk.start_transaction."
"The transaction will not be sent to Sentry. To fix, start the transaction by"
"passing it to sentry_sdk.start_transaction."
)

super().__enter__()

if self._profile is not None:
Expand Down
16 changes: 16 additions & 0 deletions tests/tracing/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,19 @@ def test_transaction_dropeed_sampled_false(sentry_init):
mock_logger.debug.assert_any_call(
"Discarding transaction because it was not started with sentry_sdk.start_transaction"
)


def test_transaction_not_started_warning(sentry_init):
sentry_init(enable_tracing=True)

tx = Transaction()

with mock.patch("sentry_sdk.tracing.logger") as mock_logger:
with tx:
pass

mock_logger.warning.assert_any_call(
"Transaction was entered without being started with sentry_sdk.start_transaction."
"The transaction will not be sent to Sentry. To fix, start the transaction by"
"passing it to sentry_sdk.start_transaction."
)

0 comments on commit c2af1b0

Please sign in to comment.