Skip to content

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:

Classes

DummySpan

Python
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:

Functions

set_tag
Python
set_tag(*args: Any, **kwargs: Any) -> DummySpan

No-op tag setter.

Returns:

  • DummySpan

    Returns self for method chaining.

set_data
Python
set_data(*args: Any, **kwargs: Any) -> DummySpan

No-op data setter.

Returns:

  • DummySpan

    Returns self for method chaining.

set_status
Python
set_status(*args: Any, **kwargs: Any) -> DummySpan

No-op status setter.

Returns:

  • DummySpan

    Returns self for method chaining.

set_name
Python
set_name(name: str) -> DummySpan

No-op name setter.

Returns:

  • DummySpan

    Returns self for method chaining.

DummyTransaction

Python
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:

Functions

set_tag
Python
set_tag(*args: Any, **kwargs: Any) -> DummySpan

No-op tag setter.

Returns:

  • DummySpan

    Returns self for method chaining.

set_data
Python
set_data(*args: Any, **kwargs: Any) -> DummySpan

No-op data setter.

Returns:

  • DummySpan

    Returns self for method chaining.

set_status
Python
set_status(*args: Any, **kwargs: Any) -> DummySpan

No-op status setter.

Returns:

  • DummySpan

    Returns self for method chaining.

set_name
Python
set_name(name: str) -> DummySpan

No-op name setter.

Returns:

  • DummySpan

    Returns self for method chaining.

Functions

safe_set_name

Python
safe_set_name(obj: Any, name: str) -> None

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:

  • obj (Any) –

    The span or transaction object.

  • name (str) –

    The name to set.

_handle_exception_in_sentry_context

Python
_handle_exception_in_sentry_context(context_obj: Any, exception: Exception) -> None

Handle exceptions in a Sentry context (span or transaction) with consistent patterns.

Parameters:

  • context_obj (Any) –

    The Sentry span or transaction object.

  • exception (Exception) –

    The exception that occurred.

_finalize_sentry_context

Python
_finalize_sentry_context(context_obj: Any, start_time: float) -> None

Finalize a Sentry context with timing information.

Parameters:

  • context_obj (Any) –

    The Sentry span or transaction object.

  • start_time (float) –

    The start time for duration calculation.

create_instrumentation_wrapper

Python
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

Python
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:

span

Python
span(
    op: str, description: str | None = None
) -> Callable[[Callable[P, R]], Callable[P, R]]

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:

start_span

Python
start_span(op: str, name: str = '') -> Generator[DummySpan | Any]

Context manager for creating a Sentry span for a block of code.

Example: with start_span("db.query", "Fetching user data"): ...

Parameters:

  • op (str) –

    The operation name for the span.

  • name (str, default: '' ) –

    The name of the span.

Yields:

  • Union[DummySpan, Span]

    The Sentry span object or a dummy object if Sentry is not initialized.

start_transaction

Python
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

Python
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

Python
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

Python
finish_transaction_on_error() -> None

Finish the current transaction with error status.

set_span_attributes

Python
set_span_attributes(attributes: dict[str, Any]) -> None

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:

  • attributes (dict[str, Any]) –

    A dictionary where keys are the attribute names and values are the attribute values to set on the span.

set_setup_phase_tag

Python
set_setup_phase_tag(span: Any, phase: str, status: str = 'starting') -> None

Set a setup phase tag on the span.

Parameters:

  • span (Any) –

    The Sentry span to tag

  • phase (str) –

    The phase name (e.g., "database", "cogs")

  • status (str, default: 'starting' ) –

    The status ("starting" or "finished")

capture_span_exception

Python
capture_span_exception(exception: Exception, **extra_data: Any) -> None

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:

  • exception (Exception) –

    The exception to capture.

  • **extra_data (Any, default: {} ) –

    Additional data to attach to the span.

enhanced_span

Python
enhanced_span(
    op: str, name: str = "", **initial_data: Any
) -> Generator[DummySpan | Any]

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

Python
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.