tracing ¶
Sentry Instrumentation Utilities for Tracing and Performance Monitoring.
This module provides a set of decorators and context managers to simplify the instrumentation of code with Sentry transactions and spans. It standardizes the creation of performance monitoring traces and ensures that they gracefully handle cases where the Sentry SDK is not initialized by providing dummy objects.
The main components are: - Decorators (@transaction, @span): For easily wrapping entire functions or methods in a Sentry transaction or span. - Context Managers (start_transaction, start_span): For instrumenting specific blocks of code within a function. - Helper Functions: For adding contextual data to the currently active span.
Classes:
-
DummySpan–A no-op (dummy) span object for when the Sentry SDK is not initialized.
-
DummyTransaction–A no-op (dummy) transaction object for when Sentry is not initialized.
Functions:
-
safe_set_name–Safely set the name on a span or transaction object.
-
create_instrumentation_wrapper–Create an instrumentation wrapper for both sync and async functions.
-
transaction–Wrap a function with a Sentry transaction.
-
span–Wrap a function with a Sentry span.
-
start_span–Context manager for creating a Sentry span for a block of code.
-
start_transaction–Context manager for creating a Sentry transaction for a block of code.
-
get_current_span–Get the current active Sentry span.
-
add_breadcrumb–Add a breadcrumb to the current Sentry scope.
-
finish_transaction_on_error–Finish the current transaction with error status.
-
set_span_attributes–Set multiple tags and data attributes on the current active Sentry span.
-
set_setup_phase_tag–Set a setup phase tag on the span.
-
capture_span_exception–Capture an exception in the current span with consistent error handling.
-
enhanced_span–Enhanced context manager for creating a Sentry span with initial data.
-
instrument_bot_commands–Automatically instruments all bot commands with Sentry transactions.
Classes¶
DummySpan ¶
DummySpan()
A no-op (dummy) span object for when the Sentry SDK is not initialized.
This class mimics the interface of a Sentry span but performs no actions, allowing instrumentation code (with start_span(...)) to run without errors even if Sentry is disabled.
Initialize the dummy span.
Methods:
-
set_tag–No-op tag setter.
-
set_data–No-op data setter.
-
set_status–No-op status setter.
-
set_name–No-op name setter.
DummyTransaction ¶
DummyTransaction()
Bases: DummySpan
A no-op (dummy) transaction object for when Sentry is not initialized.
This inherits from DummySpan and provides a safe fallback for the start_transaction context manager.
Initialize the dummy span.
Methods:
-
set_tag–No-op tag setter.
-
set_data–No-op data setter.
-
set_status–No-op status setter.
-
set_name–No-op name setter.
Functions¶
safe_set_name ¶
Safely set the name on a span or transaction object.
This helper is used because the set_name method may not always be present on all span-like objects from Sentry, so this avoids potential AttributeError exceptions.
Parameters:
_handle_exception_in_sentry_context ¶
_finalize_sentry_context ¶
create_instrumentation_wrapper ¶
create_instrumentation_wrapper[**P, R](
func: Callable[P, R],
context_factory: Callable[[], Any],
is_transaction: bool = False,
) -> Callable[P, R]
Create an instrumentation wrapper for both sync and async functions.
This is the core helper that eliminates duplication between transaction and span decorators by providing a unified wrapper creation mechanism.
Parameters:
-
func(Callable[P, R]) –The function to wrap.
-
context_factory(Callable[[], Any]) –A factory function that creates the Sentry context (span or transaction).
-
is_transaction(bool, default:False) –Whether this is a transaction (affects status setting behavior).
Returns:
-
Callable[P, R]–The wrapped function.
transaction ¶
transaction(
op: str, name: str | None = None, description: str | None = None
) -> Callable[[Callable[P, R]], Callable[P, R]]
Wrap a function with a Sentry transaction.
This handles both synchronous and asynchronous functions automatically. It captures the function's execution time, sets the status to 'ok' on success or 'internal_error' on failure, and records exceptions.
Parameters:
-
op(str) –The operation name for the transaction (e.g., 'db.query').
-
name(Optional[str], default:None) –The name for the transaction. Defaults to the function's qualified name.
-
description(Optional[str], default:None) –A description of what the transaction is doing.
Returns:
-
Callable–The decorated function.
span ¶
Wrap a function with a Sentry span.
This should be used on functions called within an existing transaction. It automatically handles both sync and async functions, captures execution time, and records success or failure status.
Parameters:
-
op(str) –The operation name for the span (e.g., 'db.query.fetch').
-
description(Optional[str], default:None) –A description of what the span is doing. Defaults to the function's name.
Returns:
-
Callable–The decorated function.
start_span ¶
Context manager for creating a Sentry span for a block of code.
Example: with start_span("db.query", "Fetching user data"): ...
Parameters:
Yields:
-
Union[DummySpan, Span]–The Sentry span object or a dummy object if Sentry is not initialized.
start_transaction ¶
start_transaction(
op: str, name: str, description: str = ""
) -> Generator[DummyTransaction | Any]
Context manager for creating a Sentry transaction for a block of code.
Example: with start_transaction("task", "process_daily_report"): ...
Parameters:
-
op(str) –The operation name for the transaction.
-
name(str) –The name for the transaction.
-
description(str, default:'') –A description of what the transaction is doing.
Yields:
-
Union[DummyTransaction, Transaction]–The Sentry transaction object or a dummy object if Sentry is not initialized.
get_current_span ¶
get_current_span() -> Any | None
Get the current active Sentry span.
Returns:
-
Any | None–The current span if Sentry is initialized, None otherwise.
add_breadcrumb ¶
add_breadcrumb(
message: str,
category: str = "default",
level: str = "info",
data: dict[str, Any] | None = None,
) -> None
Add a breadcrumb to the current Sentry scope.
finish_transaction_on_error ¶
finish_transaction_on_error() -> None
Finish the current transaction with error status.
set_span_attributes ¶
Set multiple tags and data attributes on the current active Sentry span.
This helper function simplifies attaching context to a span by accepting a dictionary of attributes. Keys are automatically treated as tags.
Parameters:
set_setup_phase_tag ¶
capture_span_exception ¶
Capture an exception in the current span with consistent error handling.
This consolidates the common pattern of setting span status and data when an exception occurs.
Parameters:
enhanced_span ¶
Enhanced context manager for creating a Sentry span with initial data.
This extends the basic start_span with the ability to set initial tags and data, reducing boilerplate in calling code.
Parameters:
-
op(str) –The operation name for the span.
-
name(str, default:'') –The name for the span.
-
**initial_data(Any, default:{}) –Initial data to set on the span.
Yields:
-
Union[DummySpan, Span]–The Sentry span object or a dummy object if Sentry is not initialized.
instrument_bot_commands ¶
instrument_bot_commands(bot: Bot) -> None
Automatically instruments all bot commands with Sentry transactions.
This function iterates through all registered commands on the bot and wraps their callbacks with the @transaction decorator. This ensures that every command invocation is captured as a Sentry transaction.
Parameters:
-
bot(Bot) –The instance of the bot whose commands should be instrumented.