API Docs#
- class sentry_sdk.Scope(ty=None, client=None)[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)[source]#
Adds an attachment to future events sent from this scope.
The parameters are the same as for the
sentry_sdk.attachments.Attachmentconstructor.- Return type:
- add_error_processor(func, cls=None)[source]#
Register a scope local error processor on the scope.
- Parameters:
func (
Callable[[Event,Union[tuple[Type[BaseException],BaseException,Optional[TracebackType]],tuple[None,None,None]]],Optional[Event]]) – A callback that works similar to an event processor but is invoked with the original exception info triple as second argument.cls (
Optional[Type[BaseException]]) – Optionally, only process exceptions of this type.
- Return type:
- 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, scope=None, **scope_kwargs)[source]#
Captures an event.
Merges given scope data and calls
sentry_sdk.client._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.scope (
Optional[Scope]) – An optionalsentry_sdk.Scopeto 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 seesentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.
- Return type:
- Returns:
An event_id if the SDK decided to send the event (see
sentry_sdk.client._Client.capture_event()).
- capture_exception(error=None, scope=None, **scope_kwargs)[source]#
Captures an exception.
- Parameters:
error (
Union[BaseException,tuple[Type[BaseException],BaseException,Optional[TracebackType]],tuple[None,None,None],None]) – An exception to capture. If None, sys.exc_info() will be used.scope (
Optional[Scope]) – An optionalsentry_sdk.Scopeto 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 seesentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.
- Return type:
- Returns:
An event_id if the SDK decided to send the event (see
sentry_sdk.client._Client.capture_event()).
- capture_message(message, level=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.scope (
Optional[Scope]) – An optionalsentry_sdk.Scopeto 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 seesentry_sdk.Scope.update_from_kwargs(). The scope and scope_kwargs parameters are mutually exclusive.
- Return type:
- Returns:
An event_id if the SDK decided to send the event (see
sentry_sdk.client._Client.capture_event()).
- property fingerprint#
When set this overrides the default fingerprint.
- generate_propagation_context(incoming_data=None)[source]#
Makes sure the propagation context is set on the scope. 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:
- get_baggage(*args, **kwargs)[source]#
Returns the Sentry “baggage” header containing trace information from the currently active span or the scopes Propagation Context.
- Return type:
Optional[Baggage]
- classmethod get_client()[source]#
- Return type:
Added in version 2.0.0.
Returns the currently used
sentry_sdk.Client. This checks the current scope, the isolation scope and the global scope for a client. If no client is available asentry_sdk.client.NonRecordingClientis returned.
- classmethod get_current_scope()[source]#
- Return type:
Added in version 2.0.0.
Returns the current scope.
- classmethod get_global_scope()[source]#
- Return type:
Added in version 2.0.0.
Returns the global scope.
- classmethod get_isolation_scope()[source]#
- Return type:
Added in version 2.0.0.
Returns the isolation scope.
- get_traceparent(*args, **kwargs)[source]#
Returns the Sentry “sentry-trace” header (aka the traceparent) from the currently active span or the scopes Propagation Context.
- iter_trace_propagation_headers(*args, **kwargs)[source]#
Return HTTP headers which allow propagation of trace data.
If a span is given, the trace data will taken from the span. If no span is given, the trace data is taken from the scope.
- classmethod last_event_id()[source]#
-
Added in version 2.2.0.
Returns event ID of the event most recently captured by the isolation scope, or None if no event has been captured. We do not consider events that are dropped, e.g. by a before_send hook. Transactions also are not considered events in this context.
The event corresponding to the returned event ID is NOT guaranteed to actually be sent to Sentry; whether the event is sent depends on the transport. The event could be sent later or not at all. Even a sent event could fail to arrive in Sentry due to network issues, exhausted quotas, or various other reasons.
- remove_attribute(attribute)[source]#
Remove an attribute if set on the scope. No-op if there is no such attribute.
- Return type:
- 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:
- run_error_processors(event, hint)[source]#
Runs the error processors on the event and returns the modified event.
- Return type:
Optional[Event]
- run_event_processors(event, hint)[source]#
Runs the event processors on the event and returns the modified event.
- Return type:
Optional[Event]
- set_attribute(attribute, value)[source]#
Set an attribute on the scope.
Any attributes-based telemetry (logs, metrics, streamed spans) captured while this scope is active will inherit attributes set on the scope.
- Return type:
- set_attributes(attributes)[source]#
Set multiple attributes on the scope.
Any attributes-based telemetry (logs, metrics, streamed spans) captured while this scope is active will inherit attributes set on the scope.
- Return type:
- set_client(client=None)[source]#
Added in version 2.0.0.
Sets the client for this scope.
- Parameters:
client (
Optional[BaseClient]) – The client to use in this scope. If None the client of the scope will be replaced by asentry_sdk.NonRecordingClient.- Return type:
- classmethod set_current_scope(new_current_scope)[source]#
- Return type:
Added in version 2.0.0.
Sets the given scope as the new current scope overwriting the existing current scope. :type new_current_scope:
Scope:param new_current_scope: The scope to set as the new current scope.
- classmethod set_isolation_scope(new_isolation_scope)[source]#
- Return type:
Added in version 2.0.0.
Sets the given scope as the new isolation scope overwriting the existing isolation scope. :type new_isolation_scope:
Scope:param new_isolation_scope: The scope to set as the new isolation scope.
- set_new_propagation_context()[source]#
Creates a new propagation context and sets it as _propagation_context. Overwriting existing one.
- Return type:
- set_tags(tags)[source]#
Sets multiple tags at once.
This method updates multiple tags at once. The tags are passed as a dictionary or other mapping type.
Calling this method is equivalent to calling set_tag on each key-value pair in the mapping. If a tag key already exists in the scope, its value will be updated. If the tag key does not exist in the scope, the key-value pair will be added to the scope.
This method only modifies tag keys in the tags mapping passed to the method. scope.set_tags({}) is, therefore, a no-op.
- set_transaction_name(name, source=None)[source]#
Set the transaction name and optionally the transaction source.
- Return type:
- start_span(name, attributes, parent_span, active, links=None)[source]#
Start a span.
The span’s parent, unless provided explicitly via the parent_span argument, will be the current active span, if any. If there is none, this span will become the root of a new span tree. If you explicitly want this span to be top-level without a parent, set parent_span=None.
start_span()can either be used as context manager or you can use the span object it returns and explicitly end it viaspan.end(). The following is equivalent:import sentry_sdk with sentry_sdk.start_span(name="My Span"): # do something # The span automatically finishes once the ``with`` block is exited
import sentry_sdk span = sentry_sdk.start_span(name="My Span") # do something span.end()
To continue a trace from another service, call sentry_sdk.continue_trace() prior to creating a top-level span.
- Parameters:
name (str) – The name to identify this span by.
attributes ("Optional[Attributes]") – Key-value attributes to set on the span from the start. These will also be accessible in the traces sampler.
parent_span ("Optional[Span]") – A span instance that the new span should consider its parent. If not provided, the parent will be set to the currently active span, if any. If set to None, this span will become a new root-level span.
active (bool) – Controls whether spans started while this span is running will automatically become its children. That’s the default behavior. If you want to create a span that shouldn’t have any children (unless provided explicitly via the parent_span argument), set this to False.
links ("Optional[list[SpanLink]]") – Spans to link the span to, without making them its parent, e.g. in other traces. More can be added with span.add_link() or span.add_links().
- Returns:
The span that has been started.
- Return type:
Span
- 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:
- trace_propagation_meta(*args, **kwargs)[source]#
Return meta tags which should be injected into HTML templates to allow propagation of trace information.
- Return type:
- class sentry_sdk.Client(dsn=None, *, max_breadcrumbs=100, release=None, environment=None, server_name=None, shutdown_timeout=2, integrations=[], ignore_spans=None, in_app_include=[], in_app_exclude=[], default_integrations=True, dist=None, transport=None, transport_queue_size=100, sample_rate=1.0, data_collection={}, http_proxy=None, https_proxy=None, ignore_errors=[], max_request_body_size='medium', socket_options=None, keep_alive=None, before_send=None, before_breadcrumb=None, debug=None, attach_stacktrace=True, ca_certs=None, traces_sample_rate=None, trace_lifecycle=None, traces_sampler=None, profiler_mode=None, profile_lifecycle='manual', profile_session_sample_rate=None, auto_enabling_integrations=True, disabled_integrations=None, auto_session_tracking=True, send_client_reports=True, _experiments={}, proxy_headers=None, project_root=None, trace_propagation_targets=['.*'], functions_to_trace=[], max_value_length=None, enable_backpressure_handling=True, error_sampler=None, enable_db_query_source=True, db_query_source_threshold_ms=100, enable_http_request_source=True, http_request_source_threshold_ms=100, spotlight=None, cert_file=None, key_file=None, custom_repr=None, add_full_stack=False, max_stack_frames=100, before_send_log=None, before_send_metric=None, before_send_span=None, org_id=None, strict_trace_continuation=False)[source]#
- class sentry_sdk.client.BaseClient(options=None)[source]#
Added in version 2.0.0.
The basic definition of a client that is used for sending data to Sentry.
- class sentry_sdk.client.NonRecordingClient(options=None)[source]#
Added in version 2.0.0.
A client that does not send any events to Sentry. This is used as a fallback when the Sentry SDK is not yet initialized.
- 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
sentry_sdk.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 optionalsentry_sdk.Scopeto apply to events.
- Return type:
- 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:
- async close_async(timeout=None, callback=None)[source]#
Asynchronously close the client and shut down the transport. Arguments have the same semantics as
Client.flush_async().- Return type:
- async flush_async(timeout=None, callback=None)[source]#
Asynchronously wait for the current events to be sent.
- 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:
Optional[Integration]
- class sentry_sdk.Transport(options=None)[source]#
Baseclass for all transports.
A transport is used to send an event to sentry.
- abstract 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 to send all event data (including errors, transactions, crons check-ins, etc.) to Sentry.
- Return type:
- flush(timeout, callback=None)[source]#
Wait timeout seconds for the current events to be sent out.
The default implementation is a no-op, since this method may only be relevant to some transports. Subclasses should override this method if necessary.
- Return type:
- kill()[source]#
Forcefully kills the transport.
The default implementation is a no-op, since this method may only be relevant to some transports. Subclasses should override this method if necessary.
- Return type:
- record_lost_event(reason, data_category=None, item=None, *, quantity=1)[source]#
This increments a counter for event loss by reason and data category by the given positive-int quantity (default 1).
If an item is provided, the data category and quantity are extracted from the item, and the values passed for data_category and quantity are ignored.
- Return type:
- sentry_sdk.traces.StreamedSpan#
alias of
Span
- sentry_sdk.traces.NoOpStreamedSpan#
alias of
NoOpSpan
- 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)[source]#
Additional files/data to send along with an event.
This class stores attachments that can be sent along with an event. Attachments are files or other data, e.g. config or log files, that are relevant to an event. Attachments are set on the
Scope, and are sent along with all non-transaction events that are captured within theScope.To add an attachment to a
Scope, usesentry_sdk.Scope.add_attachment(). The parameters foradd_attachmentare the same as the parameters for this class’s constructor.- Parameters:
bytes (
Union[None,bytes,Callable[[],bytes]]) – Raw bytes of the attachment, or a function that returns the raw bytes. Must be provided unlesspathis provided.filename (
Optional[str]) – The filename of the attachment. Must be provided unlesspathis provided.path (
Optional[str]) – Path to a file to attach. Must be provided unlessbytesis provided.content_type (
Optional[str]) – The content type of the attachment. If not provided, it will be guessed from thefilenameparameter, if available, or thepathparameter iffilenameisNone.
- 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.
- class sentry_sdk.envelope.Envelope(headers=None, items=None)[source]#
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular, each envelope may have at most one Item with type “event”.