API Docs

class sentry_sdk.Hub(client_or_hub=None, scope=None)[source]

The hub wraps the concurrency management of the SDK. Each thread has its own hub but the hub might transfer with the flow of execution if context vars are available.

If the hub is used with a with statement it’s temporarily activated.

add_breadcrumb(crumb=None, hint=None, **kwargs)[source]

Adds a breadcrumb.

Parameters:
  • crumb (Optional[Dict[str, Any]]) – Dictionary with the data as the sentry v7/v8 protocol expects.

  • hint (Optional[Dict[str, Any]]) – An optional value that can be used by before_breadcrumb to customize the breadcrumbs that are emitted.

Return type:

None

bind_client(new)[source]

Binds a new client to the hub.

Return type:

None

capture_event(event, hint=None, scope=None, **scope_kwargs)[source]

Captures an event.

Alias of sentry_sdk.Scope.capture_event().

Parameters:
  • event (Event) – A ready-made event that can be directly sent to Sentry.

  • hint (Optional[Dict[str, Any]]) – Contains metadata about the event that can be read from before_send, such as the original exception object or a HTTP request object.

  • scope (Optional[Scope]) – An optional sentry_sdk.Scope to apply to events. The scope and scope_kwargs parameters are mutually exclusive.

  • scope_kwargs (Any) – Optional data to apply to event. For supported **scope_kwargs see sentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.

Return type:

Optional[str]

capture_exception(error=None, scope=None, **scope_kwargs)[source]

Captures an exception.

Alias of sentry_sdk.Scope.capture_exception().

Parameters:
Return type:

Optional[str]

Returns:

An event_id if the SDK decided to send the event (see sentry_sdk.Client.capture_event()).

capture_message(message, level=None, scope=None, **scope_kwargs)[source]

Captures a message.

Alias of sentry_sdk.Scope.capture_message().

Parameters:
  • message (str) – The string to send as the message to Sentry.

  • level (Optional[Literal['fatal', 'critical', 'error', 'warning', 'info', 'debug']]) – If no level is provided, the default level is info.

  • scope (Optional[Scope]) – An optional sentry_sdk.Scope to apply to events. The scope and scope_kwargs parameters are mutually exclusive.

  • scope_kwargs (Any) – Optional data to apply to event. For supported **scope_kwargs see sentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.

Return type:

Optional[str]

Returns:

An event_id if the SDK decided to send the event (see sentry_sdk.Client.capture_event()).

property client: Client | None

Returns the current client on the hub.

configure_scope(callback=None, continue_trace=True)[source]

Reconfigures the scope.

Parameters:

callback (Optional[Callable[[Scope], None]]) – If provided, call the callback with the current scope.

Return type:

Optional[ContextManager[Scope]]

Returns:

If no callback is provided, returns a context manager that returns the scope.

continue_trace(environ_or_headers, op=None, name=None, source=None)[source]

Sets the propagation context from environment or headers and returns a transaction.

Return type:

Transaction

end_session()[source]

Ends the current session if there is one.

Return type:

None

flush(timeout=None, callback=None)[source]

Alias for sentry_sdk.Client.flush()

Return type:

None

get_baggage()[source]

Returns Baggage either from the active span or from the scope.

Return type:

Optional[str]

get_integration(name_or_class)[source]

Returns the integration for this hub by name or class. If there is no client bound or the client does not have that integration then None is returned.

If the return value is not None the hub is guaranteed to have a client attached.

Return type:

Any

get_traceparent()[source]

Returns the traceparent either from the active span or from the scope.

Return type:

Optional[str]

iter_trace_propagation_headers(span=None)[source]

Return HTTP headers which allow propagation of trace data. Data taken from the span representing the request, if available, or the current span on the scope if not.

Return type:

Generator[Tuple[str, str], None, None]

last_event_id()[source]

Returns the last event ID. :rtype: Optional[str]

Deprecated since version 1.40.5: This function is deprecated and will be removed in a future release. The functions capture_event, capture_message, and capture_exception return the event ID directly.

pop_scope_unsafe()[source]

Pops a scope layer from the stack.

Try to use the context manager push_scope() instead.

Return type:

Tuple[Optional[Client], Scope]

push_scope(callback=None, continue_trace=True)[source]

Pushes a new layer on the scope stack.

Parameters:

callback (Optional[Callable[[Scope], None]]) – If provided, this method pushes a scope, calls callback, and pops the scope again.

Return type:

Optional[ContextManager[Scope]]

Returns:

If no callback is provided, a context manager that should be used to pop the scope again.

resume_auto_session_tracking()[source]

Resumes automatic session tracking for the current scope if disabled earlier. This requires that generally automatic session tracking is enabled.

Return type:

None

run(callback)[source]

Runs a callback in the context of the hub. Alternatively the with statement can be used on the hub directly.

Return type:

TypeVar(T)

property scope: Scope

Returns the current scope on the hub.

start_session(session_mode='application')[source]

Starts a new session.

Return type:

None

start_span(span=None, instrumenter='sentry', **kwargs)[source]

Start a span whose parent is the currently active span or transaction, if any.

The return value is a sentry_sdk.tracing.Span instance, typically used as a context manager to start and stop timing in a with block.

Only spans contained in a transaction are sent to Sentry. Most integrations start a transaction at the appropriate time, for example for every incoming HTTP request. Use sentry_sdk.start_transaction() to start a new transaction when one is not already in progress.

For supported **kwargs see sentry_sdk.tracing.Span.

Return type:

Span

start_transaction(transaction=None, instrumenter='sentry', **kwargs)[source]

Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a new child span within the transaction or any span, call the respective .start_child() method.

Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically finished at the end of the with block. If not using context managers, call the .finish() method.

When the transaction is finished, it will be sent to Sentry with all its finished child spans.

For supported **kwargs see sentry_sdk.tracing.Transaction.

Return type:

Union[Transaction, NoOpSpan]

stop_auto_session_tracking()[source]

Stops automatic session tracking.

This temporarily session tracking for the current scope when called. To resume session tracking call resume_auto_session_tracking.

Return type:

None

trace_propagation_meta(span=None)[source]

Return meta tags which should be injected into HTML templates to allow propagation of trace information.

Return type:

str

class sentry_sdk.Scope[source]

The scope holds extra information that should be sent with all events that belong to it.

add_attachment(bytes=None, filename=None, path=None, content_type=None, add_to_transactions=False)[source]

Adds an attachment to future events sent.

Return type:

None

add_breadcrumb(crumb=None, hint=None, **kwargs)[source]

Adds a breadcrumb.

Parameters:
  • crumb (Optional[Dict[str, Any]]) – Dictionary with the data as the sentry v7/v8 protocol expects.

  • hint (Optional[Dict[str, Any]]) – An optional value that can be used by before_breadcrumb to customize the breadcrumbs that are emitted.

Return type:

None

add_error_processor(func, cls=None)[source]

Register a scope local error processor on the scope.

Parameters:
Return type:

None

add_event_processor(func)[source]

Register a scope local event processor on the scope.

Parameters:

func (Callable[[Event, Dict[str, Any]], Optional[Event]]) – This function behaves like before_send.

Return type:

None

apply_to_event(event, hint, options=None)[source]

Applies the information contained on the scope to the given event.

Return type:

Optional[Event]

capture_event(event, hint=None, client=None, scope=None, **scope_kwargs)[source]

Captures an event.

Merges given scope data and calls sentry_sdk.Client.capture_event().

Parameters:
  • event (Event) – A ready-made event that can be directly sent to Sentry.

  • hint (Optional[Dict[str, Any]]) – Contains metadata about the event that can be read from before_send, such as the original exception object or a HTTP request object.

  • client (Optional[Client]) – The client to use for sending the event to Sentry.

  • scope (Optional[Scope]) – An optional sentry_sdk.Scope to apply to events. The scope and scope_kwargs parameters are mutually exclusive.

  • scope_kwargs (Any) – Optional data to apply to event. For supported **scope_kwargs see sentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.

Return type:

Optional[str]

Returns:

An event_id if the SDK decided to send the event (see sentry_sdk.Client.capture_event()).

capture_exception(error=None, client=None, scope=None, **scope_kwargs)[source]

Captures an exception.

Parameters:
Return type:

Optional[str]

Returns:

An event_id if the SDK decided to send the event (see sentry_sdk.Client.capture_event()).

capture_message(message, level=None, client=None, scope=None, **scope_kwargs)[source]

Captures a message.

Parameters:
  • message (str) – The string to send as the message.

  • level (Optional[Literal['fatal', 'critical', 'error', 'warning', 'info', 'debug']]) – If no level is provided, the default level is info.

  • client (Optional[Client]) – The client to use for sending the event to Sentry.

  • scope (Optional[Scope]) – An optional sentry_sdk.Scope to apply to events. The scope and scope_kwargs parameters are mutually exclusive.

  • scope_kwargs (Any) – Optional data to apply to event. For supported **scope_kwargs see sentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.

Return type:

Optional[str]

Returns:

An event_id if the SDK decided to send the event (see sentry_sdk.Client.capture_event()).

clear()[source]

Clears the entire scope.

Return type:

None

clear_breadcrumbs()[source]

Clears breadcrumb buffer.

Return type:

None

continue_trace(environ_or_headers, op=None, name=None, source=None)[source]

Sets the propagation context from environment or headers and returns a transaction.

Return type:

Transaction

end_session(*args, **kwargs)[source]

Ends the current session if there is one.

Return type:

None

property fingerprint

When set this overrides the default fingerprint.

generate_propagation_context(incoming_data=None)[source]

Makes sure _propagation_context is set. If there is incoming_data overwrite existing _propagation_context. if there is no incoming_data create new _propagation_context, but do NOT overwrite if already existing.

Return type:

None

get_dynamic_sampling_context()[source]

Returns the Dynamic Sampling Context from the Propagation Context. If not existing, creates a new one.

Return type:

Optional[Dict[str, str]]

get_trace_context()[source]

Returns the Sentry “trace” context from the Propagation Context.

Return type:

Any

get_traceparent(*args, **kwargs)[source]

Returns the Sentry “sentry-trace” header (aka the traceparent) from the currently active span or the scopes Propagation Context.

Return type:

Optional[str]

iter_headers()[source]

Creates a generator which returns the sentry-trace and baggage headers from the Propagation Context.

Return type:

Iterator[Tuple[str, str]]

iter_trace_propagation_headers(*args, **kwargs)[source]

Return HTTP headers which allow propagation of trace data. Data taken from the span representing the request, if available, or the current span on the scope if not.

Return type:

Generator[Tuple[str, str], None, None]

property level

When set this overrides the level.

Deprecated since version 1.0.0: Use set_level() instead.

Parameters:

value – The level to set.

remove_context(key)[source]

Removes a context.

Return type:

None

remove_extra(key)[source]

Removes a specific extra key.

Return type:

None

remove_tag(key)[source]

Removes a specific tag.

Parameters:

key (str) – Key of the tag to remove.

Return type:

None

resume_auto_session_tracking()[source]

Resumes automatic session tracking for the current scope if disabled earlier. This requires that generally automatic session tracking is enabled.

Return type:

None

set_context(key, value)[source]

Binds a context at a certain key to a specific value.

Return type:

None

set_extra(key, value)[source]

Sets an extra key to a specific value.

Return type:

None

set_level(value)[source]

Sets the level for the scope.

Parameters:

value (Literal['fatal', 'critical', 'error', 'warning', 'info', 'debug']) – The level to set.

Return type:

None

set_new_propagation_context()[source]

Creates a new propagation context and sets it as _propagation_context. Overwriting existing one.

Return type:

None

set_tag(key, value)[source]

Sets a tag for a key to a specific value.

Parameters:
  • key (str) – Key of the tag to set.

  • value (Any) – Value of the tag to set.

Return type:

None

set_transaction_name(name, source=None)[source]

Set the transaction name and optionally the transaction source.

Return type:

None

set_user(value)[source]

Sets a user for the scope.

Return type:

None

property span: Span | None

Get/set current tracing span or transaction.

start_session(*args, **kwargs)[source]

Starts a new session.

Return type:

None

start_span(span=None, instrumenter='sentry', **kwargs)[source]

Start a span whose parent is the currently active span or transaction, if any.

The return value is a sentry_sdk.tracing.Span instance, typically used as a context manager to start and stop timing in a with block.

Only spans contained in a transaction are sent to Sentry. Most integrations start a transaction at the appropriate time, for example for every incoming HTTP request. Use sentry_sdk.start_transaction() to start a new transaction when one is not already in progress.

For supported **kwargs see sentry_sdk.tracing.Span.

Return type:

Span

start_transaction(transaction=None, instrumenter='sentry', **kwargs)[source]

Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a new child span within the transaction or any span, call the respective .start_child() method.

Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically finished at the end of the with block. If not using context managers, call the .finish() method.

When the transaction is finished, it will be sent to Sentry with all its finished child spans.

For supported **kwargs see sentry_sdk.tracing.Transaction.

Return type:

Union[Transaction, NoOpSpan]

stop_auto_session_tracking(*args, **kwargs)[source]

Stops automatic session tracking.

This temporarily session tracking for the current scope when called. To resume session tracking call resume_auto_session_tracking.

Return type:

None

trace_propagation_meta(*args, **kwargs)[source]

Return meta tags which should be injected into HTML templates to allow propagation of trace information.

Return type:

str

property transaction: Any

Return the transaction (root span) in the scope, if any.

update_from_kwargs(user=None, level=None, extras=None, contexts=None, tags=None, fingerprint=None)[source]

Update the scope’s attributes.

Return type:

None

update_from_scope(scope)[source]

Update the scope with another scope’s data.

Return type:

None

property user

When set a specific user is bound to the scope. Deprecated in favor of set_user.

class sentry_sdk.Client(dsn=None, max_breadcrumbs=100, release=None, environment=None, server_name=None, shutdown_timeout=2, integrations=[], in_app_include=[], in_app_exclude=[], default_integrations=True, dist=None, transport=None, transport_queue_size=100, sample_rate=1.0, send_default_pii=False, http_proxy=None, https_proxy=None, ignore_errors=[], max_request_body_size='medium', socket_options=None, keep_alive=False, before_send=None, before_breadcrumb=None, debug=None, attach_stacktrace=False, ca_certs=None, propagate_traces=True, traces_sample_rate=None, traces_sampler=None, profiles_sample_rate=None, profiles_sampler=None, profiler_mode=None, auto_enabling_integrations=True, auto_session_tracking=True, send_client_reports=True, _experiments={}, proxy_headers=None, instrumenter='sentry', before_send_transaction=None, project_root=None, enable_tracing=None, include_local_variables=True, include_source_context=True, trace_propagation_targets=['.*'], functions_to_trace=[], event_scrubber=None, max_value_length=1024, enable_backpressure_handling=True, error_sampler=None, enable_db_query_source=True, db_query_source_threshold_ms=100, spotlight=None)[source]
class sentry_sdk.client._Client(*args, **kwargs)[source]

The client is internally responsible for capturing the events and forwarding them to sentry through the configured transport. It takes the client options as keyword arguments and optionally the DSN as first argument.

Alias of Client. (Was created for better intelisense support)

capture_event(event, hint=None, scope=None)[source]

Captures an event.

Parameters:
  • event (Event) – A ready-made event that can be directly sent to Sentry.

  • hint (Optional[Dict[str, Any]]) – Contains metadata about the event that can be read from before_send, such as the original exception object or a HTTP request object.

  • scope (Optional[Scope]) – An optional sentry_sdk.Scope to apply to events. The scope and scope_kwargs parameters are mutually exclusive.

Return type:

Optional[str]

Returns:

An event ID. May be None if there is no DSN set or of if the SDK decided to discard the event for other reasons. In such situations setting debug=True on init() may help.

close(timeout=None, callback=None)[source]

Close the client and shut down the transport. Arguments have the same semantics as Client.flush().

Return type:

None

property dsn: str | None

Returns the configured DSN as string.

flush(timeout=None, callback=None)[source]

Wait for the current events to be sent.

Parameters:
  • timeout (Optional[float]) – Wait for at most timeout seconds. If no timeout is provided, the shutdown_timeout option value is used.

  • callback (Optional[Callable[[int, float], None]]) – Is invoked with the number of pending events and the configured timeout.

Return type:

None

get_integration(name_or_class)[source]

Returns the integration for this client by name or class. If the client does not have that integration then None is returned.

Return type:

Any

class sentry_sdk.Transport(options=None)[source]

Baseclass for all transports.

A transport is used to send an event to sentry.

capture_envelope(envelope)[source]

Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data submitted to Sentry. We use it for transactions and sessions, but regular “error” events should go through capture_event for backwards compat.

Return type:

None

capture_event(event)[source]

This gets invoked with the event dictionary when an event should be sent to sentry.

Return type:

None

flush(timeout, callback=None)[source]

Wait timeout seconds for the current events to be sent out.

Return type:

None

kill()[source]

Forcefully kills the transport.

Return type:

None

record_lost_event(reason, data_category=None, item=None)[source]

This increments a counter for event loss by reason and data category.

Return type:

None

class sentry_sdk.HttpTransport(options)[source]

The default HTTP transport.

capture_envelope(envelope)[source]

Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data submitted to Sentry. We use it for transactions and sessions, but regular “error” events should go through capture_event for backwards compat.

Return type:

None

capture_event(event)[source]

This gets invoked with the event dictionary when an event should be sent to sentry.

Return type:

None

flush(timeout, callback=None)[source]

Wait timeout seconds for the current events to be sent out.

Return type:

None

kill()[source]

Forcefully kills the transport.

Return type:

None

record_lost_event(reason, data_category=None, item=None)[source]

This increments a counter for event loss by reason and data category.

Return type:

None

class sentry_sdk.tracing.Transaction(**kwargs: Any)[source]

The Transaction is the root element that holds all the spans for Sentry performance instrumentation.

property containing_transaction: Transaction

The root element of the span tree. In the case of a transaction it is the transaction itself.

finish(hub=None, end_timestamp=None)[source]

Finishes the transaction and sends it to Sentry. All finished spans in the transaction will also be sent to Sentry.

Parameters:
  • hub (Optional[Hub]) – The hub to use for this transaction. If not provided, the current hub will be used.

  • end_timestamp (Union[float, datetime, None]) – Optional timestamp that should be used as timestamp instead of the current time.

Return type:

Optional[str]

Returns:

The event ID if the transaction was sent to Sentry, otherwise None.

get_baggage()[source]

Returns the Baggage associated with the Transaction.

The first time a new baggage with Sentry items is made, it will be frozen.

Return type:

Baggage

set_context(key, value)[source]

Sets a context. Transactions can have multiple contexts and they should follow the format described in the “Contexts Interface” documentation.

Parameters:
  • key (str) – The name of the context.

  • value (Any) – The information about the context.

Return type:

None

set_http_status(http_status)[source]

Sets the status of the Transaction according to the given HTTP status.

Parameters:

http_status (int) – The HTTP status code.

Return type:

None

to_json()[source]

Returns a JSON-compatible representation of the transaction.

Return type:

Dict[str, Any]

class sentry_sdk.tracing.Span(**kwargs: Any)[source]

A span holds timing information of a block of code. Spans can have multiple child spans thus forming a span tree.

property containing_transaction: Transaction | None

The Transaction that this span belongs to. The Transaction is the root of the span tree, so one could also think of this Transaction as the “root span”.

classmethod continue_from_environ(environ, **kwargs)[source]

Create a Transaction with the given params, then add in data pulled from the sentry-trace and baggage headers from the environ (if any) before returning the Transaction.

This is different from continue_from_headers() in that it assumes header names in the form HTTP_HEADER_NAME - such as you would get from a WSGI/ASGI environ - rather than the form header-name.

Parameters:

environ (Mapping[str, str]) – The ASGI/WSGI environ to pull information from.

Return type:

Transaction

classmethod continue_from_headers(headers, **kwargs)[source]

Create a transaction with the given params (including any data pulled from the sentry-trace and baggage headers).

Parameters:

headers (Mapping[str, str]) – The dictionary with the HTTP headers to pull information from.

Return type:

Transaction

finish(hub=None, end_timestamp=None)[source]

Sets the end timestamp of the span. Additionally it also creates a breadcrumb from the span, if the span represents a database or HTTP request.

Parameters:
  • hub (Optional[Hub]) – The hub to use for this transaction. If not provided, the current hub will be used.

  • end_timestamp (Union[float, datetime, None]) – Optional timestamp that should be used as timestamp instead of the current time.

Return type:

Optional[str]

Returns:

Always None. The type is Optional[str] to match the return value of sentry_sdk.tracing.Transaction.finish().

classmethod from_traceparent(traceparent, **kwargs)[source]

DEPRECATED: Use sentry_sdk.tracing.Span.continue_from_headers().

Create a Transaction with the given params, then add in data pulled from the given sentry-trace header value before returning the Transaction.

Return type:

Optional[Transaction]

iter_headers()[source]

Creates a generator which returns the span’s sentry-trace and baggage headers. If the span’s containing transaction doesn’t yet have a baggage value, this will cause one to be generated and stored.

Return type:

Iterator[Tuple[str, str]]

new_span(**kwargs)[source]

DEPRECATED: use sentry_sdk.tracing.Span.start_child() instead.

Return type:

Span

start_child(instrumenter='sentry', **kwargs)[source]

Start a sub-span from the current span or transaction.

Takes the same arguments as the initializer of Span. The trace id, sampling decision, transaction pointer, and span recorder are inherited from the current span/transaction.

Return type:

Span

timestamp: Optional[datetime]

End timestamp of span

to_baggage()[source]

Returns the Baggage associated with this Span, if any. (Taken from the root of the span tree.)

Return type:

Optional[Baggage]

to_json()[source]

Returns a JSON-compatible representation of the span.

Return type:

Dict[str, Any]

class sentry_sdk.profiler.Profile(transaction, hub=None, scheduler=None)[source]
class sentry_sdk.session.Session(sid=None, did=None, timestamp=None, started=None, duration=None, status=None, release=None, environment=None, user_agent=None, ip_address=None, errors=None, user=None, session_mode='application')[source]
class sentry_sdk.attachments.Attachment(bytes=None, filename=None, path=None, content_type=None, add_to_transactions=False)[source]
to_envelope_item()[source]

Returns an envelope item for this attachment.

Return type:

Item

class sentry_sdk.scrubber.EventScrubber(denylist=None, recursive=False)[source]
scrub_dict(d)[source]

If a dictionary is passed to this method, the method scrubs the dictionary of any sensitive data. The method calls itself recursively on any nested dictionaries ( including dictionaries nested in lists) if self.recursive is True. This method does nothing if the parameter passed to it is not a dictionary.

Return type:

None

scrub_list(lst)[source]

If a list is passed to this method, the method recursively searches the list and any nested lists for any dictionaries. The method calls scrub_dict on all dictionaries it finds. If the parameter passed to this method is not a list, the method does nothing.

Return type:

None

class sentry_sdk.monitor.Monitor(transport, interval=10)[source]

Performs health checks in a separate thread once every interval seconds and updates the internal state. Other parts of the SDK only read this state and act accordingly.

check_health()[source]

Perform the actual health checks, currently only checks if the transport is rate-limited. TODO: augment in the future with more checks.

Return type:

None

class sentry_sdk.envelope.Envelope(headers=None, items=None)[source]
class sentry_sdk.envelope.Item(payload, headers=None, type=None, content_type=None, filename=None)[source]
get_event()[source]

Returns an error event if there is one.

Return type:

Optional[Event]