Looking to upgrade from Sentry SDK 2.x to 3.x? Here's a comprehensive list of what's changed. Looking for a more digestable summary? See the guide in the docs with the most common migration patterns.
sentry_sdk.init()can no longer be used as a context manager.- The
@tracedecorator doesn't accept atemplateparameter anymore. - The option
attach_stacktraceis nowTrueby default, meaning the SDK will attach stack traces to messages. add_attachmentno longer accepts anadd_to_transactionsargument.- Cron check-ins no longer go through
before_send. Use the newbefore_send_check_inoption to modify or drop check-ins before they're sent. - If a
before_breadcrumbcallback, an event processor, or an error processor raises an exception, the breadcrumb or event is now dropped. Previously, the SDK would log the exception and continue processing the unmodified breadcrumb or event. - The top-level manual tracing API is now wired to span streaming tracing:
sentry_sdk.start_transactiondoesn't exist anymore. Usesentry_sdk.start_spaninstead.sentry_sdk.start_spanaccepts five arguments now:name(mandatory),attributes,parent_span(default: current active span),active(default:True),links(spans to link to without making them the parent; more can be added withspan.add_link()/span.add_links()).- The
@tracedecorator accepts three optional arguments:name,attributes,active(default:True). sentry_sdk.continue_traceaccepts a single dictionary with the incoming headers or environment data. It is no longer a context manager and it does not return a span/transaction anymore. A span needs to be started manually afterwards.sentry_sdk.new_traceresets the trace.
- The type hints of
sentry_sdk.set_attributeandsentry_sdk.set_attributesnow only accept primitives and lists of primitives, matchingScope.set_attributeandScope.set_attributes. Unexpected values are still passed throughrepr()at runtime.
-
The Strawberry integration won't auto-enable anymore if we detect
strawberry-graphqlis installed. Set it up manually, setting theasync_executionintegration option to eitherTrueorFalsedepending on if your app is async or sync.from sentry_sdk.integrations.strawberry import StrawberryIntegration sentry_sdk.init( integrations=[ StrawberryIntegration(async_execution=True), # or False ], ... )
-
The FastAPI and Starlette integrations no longer eagerly consume the request body. As a result, the body is only reported in events if your handler parsed it with
Request.json()orRequest.form()before the event is captured. -
The
UnraisableHookIntegrationis now enabled by default. -
We now don't suppress chained exceptions in the ASGI and asyncio integrations by default. The related
suppress_asgi_chained_exceptionsexperimental option was removed. -
In the AWS Lambda and GCP integrations, the text of the message of the warning the SDK optionally emits if a function is about to time out has changed.
-
The AWS Lambda integration no longer sets the
messaging.batch.message_countattribute on the function span. In 2.x span streaming mode, it was the length of the event if the event was a list, and1otherwise, so an SQS or SNS batch was always reported as1. The attribute is now only set on messaging spans, such as boto3 SQS and SNS spans. -
The
http.request.header.<name>span attributes set by server integrations are now lists of strings instead of strings. -
The HTTP breadcrumbs created by the stdlib (
http.client) and boto3 integrations now use different keys:http.methodis nowhttp.request.method,url(oraws.request.urlfor boto3) is nowurl.full,http.queryis nowurl.query, andhttp.fragmentis nowurl.fragment. The stdlib breadcrumb no longer containsreason. The query string is filtered according todata_collection'surl_query_paramssetting. -
The
urlfield of HTTP breadcrumbs created by the HTTPX, httpx2, pyreqwest, and AIOHTTP client integrations now contains the full URL, including the query string and fragment. The query string is filtered according todata_collection'surl_query_paramssetting. -
The breadcrumbs created by the PyMongo integration now use different keys:
db.nameis nowdb.namespace,db.systemis nowdb.system.name,db.operationis nowdb.operation.name,db.mongodb.collectionis nowdb.collection.name, andnet.peer.nameandnet.peer.portare nowserver.addressandserver.port. -
The connection breadcrumbs created by the asyncpg and aiomysql integrations now use
db.system.nameinstead ofdb.systemanddb.namespaceinstead ofdb.name. -
The ClickHouse integration no longer records query parameters (
db.params) or the query ID (db.query_id) on spans and breadcrumbs. -
The
RustTracingIntegrationno longer includes the values of tracing fields ifsend_default_piiis enabled. Passinclude_tracing_fields=Trueto the integration to include them. -
Whether the Dramatiq integration attaches message bodies to events is now controlled by
data_collection'squeuessetting instead ofhttp_bodies. -
The Celery integration no longer sets the status of task spans to error when a task raises a control flow exception (
Retry,Ignore, orReject). -
The boto3 integration now names spans
<ServiceID>.<Operation>(for example,S3.GetObjectorDynamoDB.GetItem), following OpenTelemetry semantic conventions. Previously, spans were namedaws.<service-id>.<Operation>(for example,aws.s3.GetObject). Its spans, including the span for reading a streamed response body, now also have the originauto.aws.boto3instead ofauto.http.boto3. SQS and SNS messaging calls are the exception: SQSSendMessageandSendMessageBatchare namedsend <queue name>,ReceiveMessageis namedreceive <queue name>, andDeleteMessageandDeleteMessageBatchare namedsettle <queue name>; SNSPublishandPublishBatchare namedsend <topic name>. Update any alerts, dashboards, orignore_spansrules that match on the old names or origin. -
Enabling an AI agent integration (LangChain, OpenAI Agents, or Pydantic AI) no longer disables the OpenAI, Anthropic, and Google GenAI integrations. Instead, those integrations don't create chat spans for requests made from within an agent framework's chat span, but still create other spans, such as embedding spans. The LangChain integration no longer instruments embeddings directly; embedding spans are now created by the integration of the underlying client library.
-
Whether the MCP integration records tool arguments, tool results, and prompt contents is now controlled by
data_collection's newmcpsetting ({"inputs": bool, "outputs": bool}, bothTrueby default) instead of thegen_aisetting. -
With
handled_tool_call_exceptions=True(the default), the Pydantic AI integration now reports an error for every failed tool argument validation attempt, including retries. Previously, only one error was reported per tool call. -
The Pydantic AI integration no longer sets the
gen_ai.response.streamingspan attribute. -
The
OTLPIntegrationno longer sets up a propagator by default:setup_propagatornow defaults toFalse. Distributed tracing now uses the propagators configured in OpenTelemetry (by default, W3Ctraceparentandbaggage) instead of Sentry'ssentry-traceandbaggageheaders. To get the old behavior back, setOTLPIntegration(setup_propagator=True). To propagate both W3C and Sentry headers, set up theSentryOTLPPropagatormanually instead:from opentelemetry.propagate import set_global_textmap from opentelemetry.propagators.composite import CompositePropagator from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator from sentry_sdk.integrations.otlp import SentryOTLPPropagator set_global_textmap( CompositePropagator([TraceContextTextMapPropagator(), SentryOTLPPropagator()]) )
Span ops are now a smaller, framework-neutral set.
- The OpenAI integration now emits
gen_ai.chatinstead ofgen_ai.responses. - The Cohere integration now emits
gen_ai.chatinstead ofai.chat_completions.create.cohere, andgen_ai.embeddingsinstead ofai.embeddings.create.cohere. - The TypeSafe AI integration now emits
gen_ai.decideinstead ofgen_ai.evaluate. - The Redis integration now emits
db.queryinstead ofdb.redis. - The Django integration now emits
view.renderinstead ofview.response.render,viewinstead ofview.authenticate, andfunctioninstead ofevent.django. - The Django, Starlette, Starlite, and Litestar integrations now emit
middlewareinstead ofmiddleware.django,middleware.starlette,middleware.starlette.receive,middleware.starlette.send,middleware.starlite,middleware.starlite.receive,middleware.starlite.send,middleware.litestar,middleware.litestar.receive, andmiddleware.litestar.send. - The ARQ, Celery, Django, Dramatiq, Huey, RQ, and Ray integrations now emit
queue.publishandqueue.processinstead ofqueue.submit.arq,queue.task.arq,queue.submit.celery,queue.task.celery,queue.submit.django,queue.task.dramatiq,queue.submit.huey,queue.task.huey,queue.task.rq,queue.submit.ray, andqueue.task.ray. - The Boto3 integration now emits
rpcinstead ofhttp.clientfor AWS API calls. SQS messaging calls emitqueue.publish(SendMessage,SendMessageBatch),queue.receive(ReceiveMessage), andqueue.settle(DeleteMessage,DeleteMessageBatch) instead, and SNSPublishandPublishBatchemitqueue.publish.
Deprecated GenAI span attributes were replaced with their current counterparts.
| Old attribute | New attribute |
|---|---|
gen_ai.system |
gen_ai.provider.name |
gen_ai.usage.input_tokens.cached |
gen_ai.usage.cache_read.input_tokens |
gen_ai.usage.input_tokens.cache_write |
gen_ai.usage.cache_creation.input_tokens |
gen_ai.usage.output_tokens.reasoning |
gen_ai.usage.reasoning.output_tokens |
gen_ai.response.time_to_first_token |
gen_ai.response.time_to_first_chunk |
gen_ai.tool.input |
gen_ai.tool.call.arguments |
gen_ai.tool.output |
gen_ai.tool.call.result |
mcp.tool.name |
gen_ai.tool.name |
mcp.prompt.name |
gen_ai.prompt.name |
mcp.tool.result.content |
gen_ai.tool.call.result |
mcp.tool.result.content_count |
removed |
gen_ai.request.available_tools (LangChain only) |
gen_ai.tool.definitions |
Additionally, the OpenAI integration now sets gen_ai.operation.name to chat instead of responses for Responses API calls.
- The OpenAI Agents integration no longer creates a workflow span (
<agent name> workflow) wrapping the agent run, or handoff spans (handoff from <agent> to <agent>). Agents that hand off to each other now appear as siblinginvoke_agentspans in the same trace. - The LangGraph integration no longer creates a
create_agentspan when a graph is compiled. - Invoke Agent spans created by the LangChain, LangGraph, OpenAI Agents, and Pydantic AI integrations no longer contain information about the model, request parameters, available tools, streaming, or token usage. This information is available on the child AI Client spans instead. Execute Tool spans created by the OpenAI Agents integration no longer contain model and request information either.
- The Django integration now creates spans for cache operations by default. Pass
DjangoIntegration(cache_spans=False)tosentry_sdk.init()to turn them off. - The Django integration no longer force-enables cache spans when Spotlight is active and
settings.DEBUGisTrue. Thecache_spansoption is now always respected as given.
-
The standard library logging integration is not auto-enabled by default anymore. To continue using it, add it to the
integrationslist in yoursentry_sdk.init():import sentry_sdk from sentry_sdk.integrations.logging import LoggingIntegration sentry_sdk.init( integrations=[ LoggingIntegration(), ] )
-
The
levelintegration option is now calledbreadcrumb_level. -
The
sentry_logs_levelintegration option is now calledlevel. -
The
capture_sentry_logsoption was removed. Uselevel=Noneto disable log capture. -
The
ignore_loggerhelper was renamed toignore_logger_for_events. -
The
ignore_logger_for_sentry_logshelper was renamed toignore_logger. -
SentryHandlerwas removed. UseEventHandlerinstead. -
SentryLogsHandlerwas renamed toLogsHandler. -
The
DEFAULT_EVENT_LEVELconstant was removed. -
When you enable the integration by adding
LoggingIntegrationto yoursentry_sdk.init(), it'll start capturing Sentry logs and breadcrumbs. Creating events from logs can be enabled by providing additional integration options.Old name New name Old default New default Description levelbreadcrumb_levelINFOINFOCaptures logs of that level and higher as breadcrumbs. event_levelevent_levelERRORNoneCaptures logs of that level and higher as events. sentry_logs_levellevelINFOINFOCaptures logs of that level and higher as Sentry logs. capture_sentry_logsremoved Falsen/a Allows to opt out of instrumenting logs as Sentry logs. Use level(previouslysentry_logs_level) to adjust what should be captured instead.ignore_loggerignore_logger_for_eventsn/a n/a Loggers that match this name will not create breadcrumbs and events. unignore_loggerunignore_logger_for_eventsn/a n/a Loggers that match this name will create breadcrumbs and events again. ignore_logger_for_sentry_logsignore_loggern/a n/a Loggers that match this name will not create Sentry logs. unignore_logger_for_sentry_logsunignore_loggern/a n/a Loggers that match this name will create Sentry logs again.
-
The Loguru logging integration is not auto-enabled by default anymore if you have Loguru installed. To continue using it, add it to the
integrationslist in yoursentry_sdk.init():import sentry_sdk from sentry_sdk.integrations.loguru import LoguruIntegration sentry_sdk.init( integrations=[ LoguruIntegration(), ] )
-
The
levelintegration option is now calledbreadcrumb_level. -
The
sentry_logs_levelintegration option is now calledlevel. -
The
capture_sentry_logsoption was removed. Uselevel=Noneto disable log capture. -
The
loguru_sentry_logs_handlerfunction was renamed tologuru_handler. -
The order of the
LoguruIntegrationconstructor arguments changed. If you were passing arguments positionally, switch to keyword arguments. -
When you enable the integration by adding
LoguruIntegrationto yoursentry_sdk.init(), it'll start capturing Sentry logs and breadcrumbs. Creating events from logs can be enabled by providing additional integration options.Old name New name Old default New default Description levelbreadcrumb_levelINFOINFOCaptures logs of that level and higher as breadcrumbs. event_levelevent_levelERRORNoneCaptures logs of that level and higher as events. sentry_logs_levellevelINFOINFOCaptures logs of that level and higher as Sentry logs. capture_sentry_logsremoved Falsen/a Allows to opt out of instrumenting logs as Sentry logs. Use level(previouslysentry_logs_level) to adjust what should be captured instead.
- Exception groups in exception chains are now properly unfurled.
- The
DedupeIntegrationnow marks each exception it has seen and drops any subsequent event for the same exception instance, regardless of where it's captured. Previously, only consecutive captures of the same exception in the same context were deduplicated. Note that this also applies if the first event was dropped, for example bybefore_sendor sampling. TheDedupeIntegration.reset_last_seenmethod was removed. - We changed the way we emit warnings. Deprecations will from now on be always emitted using
warnings.warn(), while all other warnings will be emitted usinglogger.warning().
- The SDK no longer supports Python 3.6. The oldest supported version is now 3.7.
- Dropped support for Django versions below 2.0.
- Dropped support for gevent versions below 20.9.
- Dropped support for greenlet versions below 0.4.17.
- Dropped support for Falcon versions below 3.0.
- Dropped support for Flask below 2.0.
- Dropped support for Chalice below 1.22.
- Dropped support for aiohttp below 3.7.
- Dropped support for Starlette below 0.20.
- Dropped support for FastAPI below 0.85.
- Dropped support for trytond below 5.4.
- Dropped support for Pyramid below 2.0.
- Dropped support for rq below 1.0.
- Dropped support for Quart below 0.19.
- Dropped support for Sanic below 22.0.
- Dropped support for Celery below 5.0.
- Dropped support for SQLAlchemy below 1.4.
- Dropped support for Huey below 2.0.
- Dropped support for Litestar below 2.0.
- Dropped support for PySpark below 3.0.
- Dropped support for redis-py below 3.4.1.
- Dropped support for Pydantic AI below 1.76.
- Dropped support for OpenAI Agents below 0.10.3.
- Dropped support for MCP below 2.0.
- The dedicated instrumentation for the standalone
fastmcppackage was removed.fastmcpservers are now instrumented via the underlyingmcppackage, so onlyfastmcpversions that are compatible withmcp>=2.0are supported. - Dropped support for Hugging Face Hub below 2.0.
- The following integrations now enforce their minimum supported version and won't be enabled if an older version of the package is installed:
- Apache Beam 2.12
- Cohere 5.4.0
- Dramatiq 1.9
- Google GenAI 1.29.0
- gRPC 1.32.0
- HTTPX 0.16.0
- LangChain 0.1.0
- LangGraph 0.6.6
- LaunchDarkly 9.8.0
- LiteLLM 1.77.5
- Loguru 0.7.0
- OpenAI 1.0.0
- OpenFeature 0.7.1
- PyMongo 3.5.0
- pyreqwest 0.11.6
- Starlite 1.48
- Typer 0.15
- Unleash 6.0.1
- The
send_default_piioption was removed. Usedata_collectioninstead, which gives you granular control over what data the SDK collects. Note that thedata_collectiondefaults collect more data thansend_default_pii=Falsedid. See Migrating fromsend_default_piitodata_collectionfor how to restore the previous behaviour. - The
enable_tracingoption was removed. Usetraces_sample_rate=1.0instead. - The
enable_logsoption was removed. Using Sentry's logging API now works without requiring settingenable_logs=True. - The
enable_metricsoption was removed. - The deprecated
@ai_trackdecorator was removed. - The deprecated
record_token_usagefunction was removed. - The
sentry_sdk.ai.monitoringmodule was removed, including theset_ai_pipeline_nameandget_ai_pipeline_namefunctions. - The deprecated
push_scopeandconfigure_scopeAPIs have been removed. Usewith new_scope():to push a new scope andscope = get_current_scope()to retrieve the current scope instead. - The experimental
max_spansoption was removed. - The experimental
before_send_logoption was removed. Use the top-levelbefore_send_loginstead. - The experimental
before_send_metricoption was removed. Use the top-levelbefore_send_metricinstead. - The experimental
ignore_spansoption was removed. Use the top-levelignore_spansinstead. - The experimental
before_send_spanoption was removed. Use the top-levelbefore_send_spaninstead. before_send_transactionwas removed alongside transaction-based tracing. Usebefore_send_spaninstead to modify a span before it's sent. Note thatbefore_send_spancan't drop spans. Useignore_spansfor that.- Removed the
auto_session_trackingdecorator, as well asauto_session_tracking_scope,is_auto_session_tracking_enabled, andis_auto_session_tracking_enabled_scope. Usetrack_sessioninstead. - The deprecated
set_measurementAPI was removed. - The
include_local_variablesoption was removed. Usedata_collection'sstack_frame_variablesas a drop-in replacement. - The
include_source_contextoption was removed. Usedata_collection'sframe_context_linesfor more granular control over the source context reported by specifying the number of lines to include around the failing line, or setframe_context_lines=0to disable source context entirely. - The
event_scrubberoption and thesentry_sdk.scrubbermodule (EventScrubber,DEFAULT_DENYLIST,DEFAULT_PII_DENYLIST) were removed. Usedata_collectionto control what data is collected, andbefore_sendfor custom scrubbing. Note that local variables in stack frames are no longer scrubbed by default. To filter out sensitive variables (such aspasswordortoken), setdata_collection'sstack_frame_variablesto{"mode": "denylist"}. You can add your own terms with"terms": [...]. - Transaction profiling and related code was removed, including the
profiles_sample_rateandprofiles_sampleroptions and thesleepvalue ofprofiler_mode. Use continuous profiling instead, configured withprofile_session_sample_rateandprofile_lifecycle. The transaction-profiler exports fromsentry_sdk.profiler(Profile,Scheduler,ThreadScheduler,GeventScheduler,setup_profiler,teardown_profiler,has_profiling_enabled,MAX_PROFILE_DURATION_NS,PROFILE_MINIMUM_SAMPLES) were removed as well. - The
start_profile_sessionandstop_profile_sessionwere removed in favor ofstart_profilerandstop_profiler, respectively. - The experimental
continuous_profiling_modeoption was removed. Use the top-levelprofiler_mode, instead. - Removed the deprecated Hub class and all uses of hub throughout the SDK in arguments, options, etc. Use a scope instead.
- The
data_collectionoption is no longer accessible under_experiments. Use it as a top-level option instead. - The experimental
record_sql_paramsoption was removed. Use thedatabase_query_datasetting ofdata_collectioninstead. - The deprecated
propagate_tracesoption has been removed. Usetrace_propagation_targetsinstead, which gives you more power over trace propagation. Note that only the top-levelinitoption was removed; thepropagate_tracesoption of the Celery integration remains available. - The
trace_ignore_status_codesoption was removed. - The
update_current_spanAPI was removed. - The
sentry_sdk.tracingmodule was removed, including theSpan,Transaction,NoOpSpan, andTransactionSourceclasses. Import tracing primitives fromsentry_sdk.tracesinstead.TransactionSourcewas replaced bysentry_sdk.traces.SegmentNameSource, which has the same values. The span classes from 2.x's span streaming mode,sentry_sdk.traces.StreamedSpanandNoOpStreamedSpan, are now calledSpanandNoOpSpan; the old names remain available as aliases. - The
stream_gen_ai_spansoption was removed. All spans are streamed now. If you previously setstream_gen_ai_spans=False, note that GenAI integrations no longer truncate messages (previously, only the last message was kept and truncated), and the OpenAI, Anthropic, LangChain, LiteLLM, and OpenAI Agents integrations no longer replace binary content in messages (for example, base64-encoded images) with[Filtered]. To prevent prompts and responses from being sent, setdata_collection'sgen_aiinputsand/oroutputstoFalse. - Span streaming is now the only tracing mode. The experimental
trace_lifecycleoption was removed. The top-leveltrace_lifecycleoption is still accepted, but any value other than"stream"is ignored and logs a warning.
- Removed the
transaction_styleoption from server integrations (DjangoIntegration,StarletteIntegration,FastApiIntegration,AioHttpIntegration,FlaskIntegration,PyramidIntegration,QuartIntegration,BottleIntegration,FalconIntegration,StarliteIntegration,LitestarIntegrationandSentryAsgiMiddleware). Segments are now always named after the route pattern (for example,/users/<id>). For the Flask, Quart, Bottle, Pyramid, and AIOHTTP integrations, this changes the default segment names, which were previously based on the endpoint, route, or handler name. Update any alerts, dashboards, orignore_spansrules that match on the old names. - Removed the
include_promptsoption from GenAI integrations (AnthropicIntegration,CohereIntegration,GoogleGenAIIntegration,HuggingfaceHubIntegration,LangchainIntegration,LanggraphIntegration,LiteLLMIntegration,MCPIntegration,OpenAIIntegrationandPydanticAIIntegration) - Removed the
LangchainIntegration'smax_spansoption. - Removed the
RedisIntegration'smax_data_sizeoption. - Removed the possibility to supply a specific client to the
LaunchDarklyIntegration. - The
SentrySpanProcessor,SentryPropagator,instrumenter, and associated OpenTelemetry compatibility code was removed along with theopentelemetryextra and theSentryPropagatorentrypoint. Use theOTLPIntegrationinstead. - The experimental option
otel_powered_performancehas been removed together with the associatedOpenTelemetryIntegrationandopentelemetry-experimentalextra. - The
failed_request_status_codesintegration option now only supports a set of integers as input. Lists of integers or containers of integers are no longer supported. - Removed Spotlight integration for Django. The SDK no longer injects
sentry_sdk.spotlight.SpotlightMiddlewareinto your Django middleware when Spotlight is enabled andDEBUGisTrue, and the middleware itself was removed. TheSENTRY_SPOTLIGHT_ON_ERRORandSENTRY_SPOTLIGHT_MIDDLEWAREenvironment variables have no effect anymore. See Spotlight 2.0 for more context. - The deprecated parameter
propagate_hubinThreadingIntegration()was removed. - The
unsafe_context_dataparameter ofSentryAsgiMiddlewarewas removed. If you were passing arguments toSentryAsgiMiddlewarepositionally, switch to keyword arguments, since the position of the remaining parameters has changed. - The
max_spansoption of theLangchainIntegrationwas removed. SanicIntegrationno longer acceptsunsampled_statuses.- The
hash_querymethod of the Strawberry integration'sSentryAsyncExtensionandSentrySyncExtensionwas removed, along with thegraphql.resource_namespan attribute. - The
record_paramsoption ofAsyncPGIntegrationandAioMySQLIntegrationwas removed. Use thedatabase_query_datasetting ofdata_collectioninstead.
- A number of extras (installable via
sentry-sdk[extra-name]) has been removed. Use the base package (sentry-sdk) instead; there is no difference in functionality. The following extras have been removed:aiohttp,anthropic,arq,asyncpg,beam,bottle,celery,celery-redbeat,chalice,clickhouse-driver,django,falcon,fastapi,google-genai,httpx,huey,huggingface_hub,langchain,langgraph,launchdarkly,litellm,litestar,loguru,mcp,openai,openfeature,pydantic_ai,pymongo,pyspark,rq,sanic,sqlalchemy,starlette,starlite,statsig,tornado,unleash. configure_debug_hubwas removed.Baggage.from_optionswas removed.Transport.capture_eventwas removed. UseTransport.capture_envelopeinstead.Envelope.add_transaction,Envelope.add_profile,Envelope.get_transaction_event, andItem.get_transaction_eventwere removed.sentry_sdk.utils.event_from_exceptionno longer accepts aclient_optionsargument. The current client's options are used instead. If you were passing arguments positionally, note thatmechanismis now the second positional argument.- Function transports were removed.
- The
Scope.trace_propagation_metafunction no longer accepts aspanas argument. - Direct assignment to
Scope.levelwas removed. Usesentry_sdk.set_levelinstead. - Direct assignment to
Scope.userwas removed. Usesentry_sdk.set_userinstead. Scope.iter_headerswas removed.Scope.start_transaction,Scope.start_streamed_span, andScope.continue_tracewere removed. Use the top-levelsentry_sdk.start_spanandsentry_sdk.continue_traceinstead.- The
SPANSTATUS,SPANTEMPLATE, andINSTRUMENTERconstants were removed fromsentry_sdk.consts. - The SDK won't set any tags on its own anymore. As a consequence, events passed to
before_send(and other event processors) will not have a"tags"key unless tags were set explicitly (e.g. viasentry_sdk.set_tag) or by an integration. If you accessevent["tags"]directly, useevent.get("tags", {})orevent.setdefault("tags", {})instead.
The new data_collection defaults collect more data than send_default_pii did. User identity, generative AI content, HTTP request/response bodies, and file paths are now on by default, and more HTTP headers and cookies are collected.
If you wish to restrict data collection to roughly match the previous behaviour of send_default_pii=False, you can use the following configuration:
sentry_sdk.init(
data_collection={
"user_info": False,
"http_bodies": [],
"graphql": {
"document": False,
"variables": False,
},
"gen_ai": {
"inputs": False,
"outputs": False,
},
"mcp": {
"inputs": False,
"outputs": False,
},
"database_query_data": False,
"queues": False,
"http_headers": {
"request": {
"mode": "denylist",
"terms": ["forwarded", "-ip", "remote-", "via", "-user"],
},
},
"cookies": {
"mode": "denylist",
"terms": ["forwarded", "-ip", "remote-", "via", "-user"],
},
"url_query_params": {
"mode": "denylist",
"terms": ["forwarded", "-ip", "remote-", "via", "-user"],
},
},
)Looking to upgrade from Sentry SDK 1.x to 2.x? Here's a comprehensive list of what's changed. Looking for a more digestable summary? See the guide in the docs with the most common migration patterns.
- Additional integrations will now be activated automatically if the SDK detects the respective package is installed: Ariadne, ARQ, asyncpg, Chalice, clickhouse-driver, GQL, Graphene, huey, Loguru, PyMongo, Quart, Starlite, Strawberry.
- While refactoring the inner workings of the SDK we added new top-level APIs for custom instrumentation called
new_scopeandisolation_scope. See the Deprecated section to see how they map to the existing APIs.
-
The Pyramid integration will not capture errors that might happen in
authenticated_userid()in a customAuthenticationPolicyclass. -
A typo in the name of the
MetricsAggregatormethodneed_code_locationwas fixed. -
The
BackgroundWorkerthread used to process events was renamed fromraven-sentry.BackgroundWorkertosentry-sdk.BackgroundWorker. -
The
reraisefunction was moved fromsentry_sdk._compattosentry_sdk.utils. -
The
_ScopeManagerwas moved fromsentry_sdk.hubtosentry_sdk.scope. -
The signature for the metrics callback function set with
before_emit_metrichas changed frombefore_emit_metric(key, tags)tobefore_emit_metric(key, value, unit, tags) -
Moved the contents of
tracing_utils_py3.pytotracing_utils.py. Thestart_child_span_decoratoris now insentry_sdk.tracing_utils. -
The actual implementation of
get_current_spanwas moved tosentry_sdk.tracing_utils.sentry_sdk.get_current_spanis still accessible as part of the top-level API. -
sentry_sdk.tracing_utils.add_query_source(): Removed thehubparameter. It is not necessary anymore. -
sentry_sdk.tracing_utils.record_sql_queries(): Removed thehubparameter. It is not necessary anymore. -
sentry_sdk.tracing_utils.get_current_span()does now take ascopeinstead of ahubas parameter. -
sentry_sdk.tracing_utils.should_propagate_trace()now takes aClientinstead of aHubas first parameter. -
sentry_sdk.utils.is_sentry_url()now takes aClientinstead of aHubas first parameter. -
sentry_sdk.utils._get_contextvarsdoes not return a tuple with three values, but a tuple with two values. Thecopy_contextwas removed. -
You no longer have to use
configure_scopeto mutate a transaction. Instead, you simply get the current scope to mutate the transaction. Here is a recipe on how to change your code to make it work: Your existing implementation:transaction = sentry_sdk.transaction(...) # later in the code execution: with sentry_sdk.configure_scope() as scope: scope.set_transaction_name("new-transaction-name")
needs to be changed to this:
transaction = sentry_sdk.transaction(...) # later in the code execution: scope = sentry_sdk.get_current_scope() scope.set_transaction_name("new-transaction-name")
-
The classes listed in the table below are now abstract base classes. Therefore, they can no longer be instantiated. Subclasses can only be instantiated if they implement all of the abstract methods.
Show table
Class Abstract methods sentry_sdk.integrations.Integrationsetup_oncesentry_sdk.metrics.Metricadd,serialize_value, andweightsentry_sdk.profiler.Schedulersetupandteardownsentry_sdk.transport.Transportcapture_envelope
- Removed support for Python 2 and Python 3.5. The SDK now requires at least Python 3.6.
- Removed support for Celery 3.*.
- Removed support for Django 1.8, 1.9, 1.10.
- Removed support for Flask 0.*.
- Removed support for gRPC < 1.39.
- Removed support for Tornado < 6.
- Removed support for sending events to the
/storeendpoint. Everything is now sent to the/envelopeendpoint. If you're on SaaS you don't have to worry about this, but if you're running Sentry yourself you'll need version20.6.0or higher of self-hosted Sentry. - The deprecated
with_localsconfiguration option was removed. Useinclude_local_variablesinstead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables. - The deprecated
request_bodiesconfiguration option was removed. Usemax_request_body_size. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size. - Removed support for
user.segment. It was also removed from the trace header as well as from the dynamic sampling context. - Removed support for the
installmethod for custom integrations. Please usesetup_onceinstead. - Removed
sentry_sdk.tracing.Span.new_span. Usesentry_sdk.tracing.Span.start_childinstead. - Removed
sentry_sdk.tracing.Transaction.new_span. Usesentry_sdk.tracing.Transaction.start_childinstead. - Removed support for creating transactions via
sentry_sdk.tracing.Span(transaction=...). To create a transaction, please usesentry_sdk.tracing.Transaction(name=...). - Removed
sentry_sdk.utils.Auth.store_api_url. sentry_sdk.utils.Auth.get_api_url's now accepts asentry_sdk.consts.EndpointTypeenum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possiblesentry_sdk.consts.EndpointTypevalue. The parameter exists for future compatibility.- Removed
tracing_utils_py2.py. Thestart_child_span_decoratoris now insentry_sdk.tracing_utils. - Removed the
sentry_sdk.profiler.Scheduler.stop_profilingmethod. Any calls to this method can simply be removed, since this was a no-op method. - Removed the experimental
metrics_summary_sample_rateconfig option. - Removed the experimental
should_summarize_metricconfig option.
-
Using the
Hubdirectly as well as using hub-based APIs has been deprecated. Where available, use the top-level API instead; otherwise use the scope API or the client API.Before:
with hub.start_span(...): # do something
After:
import sentry_sdk with sentry_sdk.start_span(...): # do something
-
Hub cloning is deprecated.
Before:
with Hub(Hub.current) as hub: # do something with the cloned hub
After:
import sentry_sdk with sentry_sdk.isolation_scope() as scope: # do something with the forked scope
-
configure_scopeis deprecated. Modify the current or isolation scope directly instead.Before:
with configure_scope() as scope: # do something with `scope`
After:
from sentry_sdk import get_current_scope scope = get_current_scope() # do something with `scope`
Or:
from sentry_sdk import get_isolation_scope scope = get_isolation_scope() # do something with `scope`
When to use
get_current_scope()andget_isolation_scope()depends on how long the change to the scope should be in effect. If you want the changed scope to affect the whole request-response cycle or the whole execution of task, use the isolation scope. If it's more localized, use the current scope. -
push_scopeis deprecated. Fork the current or the isolation scope instead.Before:
with push_scope() as scope: # do something with `scope`
After:
import sentry_sdk with sentry_sdk.new_scope() as scope: # do something with `scope`
Or:
import sentry_sdk with sentry_sdk.isolation_scope() as scope: # do something with `scope`
new_scope()will fork the current scope, whileisolation_scope()will fork the isolation scope. The lifecycle of a single isolation scope roughly translates to the lifecycle of a transaction in most cases, so if you're looking to create a new separated scope for a whole request-response cycle or task execution, go forisolation_scope(). If you want to wrap a smaller unit code, fork the current scope instead withnew_scope(). -
Accessing the client via the hub has been deprecated. Use the top-level
sentry_sdk.get_client()to get the current client. -
profiler_modeandprofiles_sample_ratehave been deprecated as_experimentsoptions. Use them as top level options instead:sentry_sdk.init( ..., profiler_mode="thread", profiles_sample_rate=1.0, )
-
Deprecated
sentry_sdk.transport.Transport.capture_event. Please usesentry_sdk.transport.Transport.capture_envelope, instead. -
Passing a function to
sentry_sdk.init'stransportkeyword argument has been deprecated. If you wish to provide a custom transport, please pass asentry_sdk.transport.Transportinstance or a subclass. -
The parameter
propagate_hubinThreadingIntegration()was deprecated and renamed topropagate_scope.