### Replace start_span, start_transaction, and start_child with sentry_sdk.traces.start_span() Source: https://docs.sentry.io/platforms/python/tracing/streamed-spans/migration-guide Shows the migration from old span creation methods to the new `sentry_sdk.traces.start_span()` API, including examples for starting a span, forcing a service span with `parent_span=None`, and starting child spans with explicit parent. ```python import sentry_sdk # Starting a span - with sentry_sdk.start_span(op="http.client", description="GET /api/users") as span: + with sentry_sdk.traces.start_span( + name="GET /api/users", + attributes={"sentry.op": "http.client"}, + ) as span: ... # Starting what used to be a transaction: pass parent_span=None to force a service span - with sentry_sdk.start_transaction(name="flow.checkout") as transaction: + with sentry_sdk.traces.start_span(name="flow.checkout", parent_span=None) as span: ... # Starting a child span: just start a span while the parent is active - with parent.start_child(op="db", description="SELECT") as child: + with sentry_sdk.traces.start_span(name="SELECT", attributes={"sentry.op": "db"}): ... # Starting a child span: if the span's parent should be a span that's currently not active, you can provide it explicitly - with parent.start_child(op="db", description="SELECT") as child: + with sentry_sdk.traces.start_span(name="SELECT", attributes={"sentry.op": "db"}, parent_span=parent): ... ``` -------------------------------- ### Install strawberry-graphql debug server Source: https://docs.sentry.io/platforms/python/integrations/strawberry Install the Strawberry GraphQL debug server, which includes the dependencies needed to run the example server. ```bash pip install 'strawberry-graphql[debug-server]' ``` -------------------------------- ### Install uvicorn Source: https://docs.sentry.io/platforms/python/integrations/ariadne Install the `uvicorn` ASGI server to run the GraphQL web server. ```bash pip install uvicorn ``` -------------------------------- ### Low-Level API Example Source: https://docs.sentry.io/platforms/python/integrations/mcp Use this example for more control over the MCP server behavior with the low-level API. It initializes Sentry, creates a low-level server, defines tools and handlers, and runs the server using stdio. The example includes list_tools and call_tool handlers. ```python import asyncio from typing import Any import sentry_sdk from sentry_sdk.integrations.mcp import MCPIntegration from mcp.server.lowlevel import Server from mcp.server import stdio from mcp.types import Tool, TextContent, GetPromptResult, PromptMessage # Initialize Sentry sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", traces_sample_rate=1.0, send_default_pii=True, integrations=[ MCPIntegration(), ], ) # Create the low-level MCP server server = Server("example-lowlevel-server") # List available tools @server.list_tools() async def list_tools() -> list[Tool]: return [ Tool( name="calculate_sum", description="Add two numbers together", inputSchema={ "type": "object", "properties": { "a": {"type": "number", "description": "First number"}, "b": {"type": "number", "description": "Second number"}, }, "required": ["a", "b"], }, ), ] # Handle tool execution @server.call_tool() async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]: if name == "calculate_sum": a = arguments.get("a", 0) b = arguments.get("b", 0) result = a + b return [TextContent(type="text", text=f"The sum is {result}")] return [TextContent(type="text", text=f"Unknown tool: {name}")] async def main(): async with stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, server.create_initialization_options(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install sentry-sdk with pip Source: https://docs.sentry.io/platforms/python/agent-tracing/litellm Install the Sentry SDK from PyPI. This is the first step to use the LiteLLM integration. ```bash pip install sentry-sdk ``` -------------------------------- ### Install sentry-sdk and typer Source: https://docs.sentry.io/platforms/python/integrations/typer Install the Sentry Python SDK and Typer CLI. ```bash pip install "sentry-sdk" "typer" ``` -------------------------------- ### Install sentry-sdk and uvicorn via pip Source: https://docs.sentry.io/platforms/python/integrations/litestar Install the Sentry SDK and uvicorn from PyPI. This is the standard installation command for the Litestar integration. ```bash pip install sentry-sdk uvicorn ``` -------------------------------- ### Configure DjangoIntegration with sentry_sdk.init() Source: https://docs.sentry.io/platforms/python/integrations/django Configure the Django integration by passing DjangoIntegration to sentry_sdk.init(). This example sets transaction_style to 'url', enables middleware_spans and signals_spans, adds a signals_denylist, disables cache_spans, and restricts http_methods_to_capture to GET. ```python import django.db.models.signals import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( # ... integrations=[ DjangoIntegration( transaction_style='url', middleware_spans=True, signals_spans=True, signals_denylist=[ django.db.models.signals.pre_init, django.db.models.signals.post_init, ], cache_spans=False, http_methods_to_capture=("GET",), ), ], ) ``` -------------------------------- ### Verify Starlite integration with example app Source: https://docs.sentry.io/platforms/python/integrations/starlite Create an app.py file with a Starlite route that raises a ZeroDivisionError. Start the server with uvicorn and access /hello to see a transaction and error in Sentry. ```python from starlite import Starlite, get sentry_sdk.init(...) # same as above @get("/hello") async def hello_world() -> str: 1 / 0 return "Hello!" app = Starlite(route_handlers=[hello_world]) ``` ```bash uvicorn app:app ``` -------------------------------- ### Install sentry-sdk with pip or uv Source: https://docs.sentry.io/platforms/python/integrations/dramatiq Install the Sentry Python SDK. The first command uses pip; the second shows the uv package manager equivalent. ```bash pip install "sentry-sdk" ``` ```bash uv pip install "sentry-sdk" ``` -------------------------------- ### FastMCP High-Level API Example Source: https://docs.sentry.io/platforms/python/integrations/mcp Use this example to set up an MCP server with Sentry using the high-level FastMCP API. It initializes Sentry with the MCPIntegration, creates a FastMCP server, and defines tools, a resource, and a prompt. The server is run with mcp.run(). ```python import sentry_sdk from sentry_sdk.integrations.mcp import MCPIntegration from mcp.server.fastmcp import FastMCP # Initialize Sentry sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", traces_sample_rate=1.0, # Add data like tool inputs/outputs; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, integrations=[ MCPIntegration(), ], ) # Create the MCP server mcp = FastMCP("Example MCP Server") # Define a tool @mcp.tool() async def calculate_sum(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool() def greet_user(name: str) -> str: """Generate a personalized greeting.""" return f"Hello, {name}! Welcome to the MCP server." # Define a resource @mcp.resource("config://settings") def get_settings() -> str: """Get server configuration settings.""" return "Server Configuration: Version 1.0.0" # Define a prompt @mcp.prompt() def code_review_prompt(language: str = "python") -> str: """Generate a code review prompt for a specific language.""" return f"You are an expert {language} code reviewer..." # Run the server mcp.run() ``` -------------------------------- ### Install sentry-sdk with opentelemetry-otlp extra Source: https://docs.sentry.io/platforms/python/integrations/otlp Installs the sentry-sdk package with the opentelemetry-otlp extra for OTLP integration. This is required before configuring the integration. ```bash pip install "sentry-sdk[opentelemetry-otlp]" ``` -------------------------------- ### Install Sentry SDK on Spark clusters Source: https://docs.sentry.io/platforms/python/integrations/spark Install the Sentry Python SDK on all clusters using an initialization script. This is required to use the Spark integration. ```bash easy_install pip pip install --upgrade sentry-sdk ``` -------------------------------- ### Start RQ worker with mysettings module Source: https://docs.sentry.io/platforms/python/integrations/rq Start your RQ worker using the `-c` flag to specify the module name of `mysettings.py`. This ensures the Sentry SDK is initialized on worker startup, which is required for error reporting to work correctly. ```shell rq worker \ -c mysettings # module name of mysettings.py ``` -------------------------------- ### Falcon integration verification example Source: https://docs.sentry.io/platforms/python/integrations/falcon Example Falcon app that initializes the Sentry SDK and defines a resource that raises an error. When accessed at http://localhost:8000/, a transaction is created in Performance and an error event is sent to sentry.io, connected to the transaction. ```python import falcon sentry_sdk.init(...) # same as above class HelloWorldResource: def on_get(self, req, resp): message = { 'hello': "world", } 1 / 0 # raises an error resp.media = message app = falcon.App() app.add_route('/', HelloWorldResource()) ``` -------------------------------- ### Run Strawberry server Source: https://docs.sentry.io/platforms/python/integrations/strawberry Start the Strawberry GraphQL web server using the schema defined in schema.py. ```bash strawberry server schema ``` -------------------------------- ### Create a test OpenTelemetry span Source: https://docs.sentry.io/platforms/python/tracing/instrumentation/opentelemetry Create a test span using the OpenTelemetry tracer. This example demonstrates how to start a span and simulate processing. ```python import time tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("test_otel_span"): print("Processing some data...") # Simulate some processing time.sleep(3) ``` -------------------------------- ### Installation: raven.Client vs sentry_sdk.init Source: https://docs.sentry.io/platforms/python/migration/raven-to-sentry-sdk Shows the old raven-python client initialization and the new sentry_sdk.init call. The new SDK uses the same DSN and release parameter. ```python import raven client = raven.Client("https://@o.ingest.sentry.io/", release="1.3.0") ``` ```python import sentry_sdk sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", release="1.3.0", ) ``` -------------------------------- ### Configure OpenTelemetry with SentrySpanProcessor and SentryPropagator Source: https://docs.sentry.io/platforms/python/tracing/instrumentation/opentelemetry Configure OpenTelemetry with the Sentry span processor and propagator. This minimal example requires no additional OpenTelemetry setup. ```python from opentelemetry import trace from opentelemetry.propagate import set_global_textmap from opentelemetry.sdk.trace import TracerProvider from sentry_sdk.integrations.opentelemetry import SentrySpanProcessor, SentryPropagator provider = TracerProvider() provider.add_span_processor(SentrySpanProcessor()) trace.set_tracer_provider(provider) set_global_textmap(SentryPropagator()) ``` -------------------------------- ### Initialize Sentry Python SDK with options Source: https://docs.sentry.io/platforms/python/configuration/options Shows how to pass options to the Sentry Python SDK's init() function as keyword arguments. Includes dsn, max_breadcrumbs, debug, traces_sample_rate, send_default_pii, and a commented-out release example. ```python import sentry_sdk sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", max_breadcrumbs=50, debug=True, # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. traces_sample_rate=1.0, # Add request headers and IP for users, # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # By default the SDK will try to use the SENTRY_RELEASE # environment variable, or infer a git commit # SHA as release, however you may want to set # something more human-readable. # release="myapp@1.0.0", ) ``` -------------------------------- ### Excluding Beat Tasks with `exclude_beat_tasks` Source: https://docs.sentry.io/platforms/python/integrations/celery/crons Configure `CeleryIntegration` with an `exclude_beat_tasks` list containing exact task names or regex patterns to ignore. In the example, `some-task-a` and tasks starting with `payment-check-` are excluded. ```python sentry_sdk.init( # ... integrations=[ CeleryIntegration( monitor_beat_tasks=True, + exclude_beat_tasks=[ + "some-task-a", + "payment-check-.*", + ] ), ], ) ``` -------------------------------- ### Configure Sentry SDK in mysettings.py Source: https://docs.sentry.io/platforms/python/integrations/rq Create a file named `mysettings.py` with this content to initialize the Sentry SDK. The `rq` package must be in your dependencies for the integration to be enabled automatically. The configuration includes options for error monitoring, tracing, and profiling; adjust the DSN and product options as needed. ```python # mysettings.py import sentry_sdk sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", # Add data like request headers and IP for users, if applicable; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # ___PRODUCT_OPTION_START___ performance # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. traces_sample_rate=1.0, # ___PRODUCT_OPTION_END___ performance # ___PRODUCT_OPTION_START___ profiling # To collect profiles for all profile sessions, # set `profile_session_sample_rate` to 1.0. profile_session_sample_rate=1.0, # Profiles will be automatically collected while # there is an active span. profile_lifecycle="trace", # ___PRODUCT_OPTION_END___ profiling ) ``` -------------------------------- ### Configure StarletteIntegration options Source: https://docs.sentry.io/platforms/python/integrations/starlette Configure StarletteIntegration options in sentry_sdk.init(). The example sets transaction_style to "endpoint", failed_request_status_codes to {403, *range(500, 599)}, middleware_spans to False, and http_methods_to_capture to ("GET",). ```python from sentry_sdk.integrations.starlette import StarletteIntegration sentry_sdk.init( # ... integrations=[ StarletteIntegration( transaction_style="endpoint", failed_request_status_codes={403, *range(500, 599)}, middleware_spans=False, http_methods_to_capture=("GET",), ) ], ) ``` -------------------------------- ### Verify AIOHTTP integration with a test transaction Source: https://docs.sentry.io/platforms/python/integrations/aiohttp/aiohttp-client This example creates a transaction named 'testing_sentry' and makes outgoing GET and POST requests using aiohttp.ClientSession. It will create spans for the outgoing HTTP requests and appear in the Performance section of sentry.io. ```python import asyncio import aiohttp async def main(): sentry_sdk.init(...) # same as above # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode with sentry_sdk.start_transaction(name="testing_sentry"): async with aiohttp.ClientSession() as session: async with session.get("https://sentry.io/") as response: print("Status:", response.status) async with session.post("http://httpbin.org/post") as response: print("Status:", response.status) asyncio.run(main()) ``` -------------------------------- ### Extract incoming tracing information with continue_trace() Source: https://docs.sentry.io/platforms/python/tracing/distributed-tracing/custom-trace-propagation Use sentry_sdk.continue_trace() to extract and store incoming tracing information from headers, environment variables, or other sources. In transaction mode, it returns a transaction but does not start it; use start_transaction() to begin. The example assumes get_incoming_headers_as_dict() returns a dictionary with tracing information. ```python import sentry_sdk from my_project import get_incoming_headers_as_dict headers = get_incoming_headers_as_dict() transaction = sentry_sdk.continue_trace(headers) with sentry_sdk.start_transaction(transaction): ... ``` -------------------------------- ### Initialize Sentry SDK with tracing, profiling, and metrics Source: https://docs.sentry.io/platforms/python Initialize the Sentry SDK in your app's entry point. Configure the DSN, enable sending PII, and optionally enable tracing, profiling, and metrics. Set traces_sample_rate to 1.0 to capture 100% of transactions. For profiling, set profile_session_sample_rate to 1.0 and profile_lifecycle to "trace" to collect profiles during active spans. ```python import sentry_sdk # ___PRODUCT_OPTION_START___ metrics from sentry_sdk import metrics # ___PRODUCT_OPTION_END___ metrics sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", # Add request headers and IP for users, # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # ___PRODUCT_OPTION_START___ performance # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. # see https://docs.sentry.io/platforms/python/configuration/options/#traces_sample_rate for more info traces_sample_rate=1.0, # ___PRODUCT_OPTION_END___ performance # ___PRODUCT_OPTION_START___ profiling # Enables continuous profiling. # To collect profiles for all profile sessions, # set `profile_session_sample_rate` to 1.0. # see https://docs.sentry.io/platforms/python/configuration/options/#profile_session_sample_rate for more info profile_session_sample_rate=1.0, # Profiles will be automatically collected while # there is an active span. # see https://docs.sentry.io/platforms/python/configuration/options/#profile_lifecycle for more info profile_lifecycle="trace", # ___PRODUCT_OPTION_END___ profiling ) ``` -------------------------------- ### Install sentry-sdk with pure_eval extra using pip Source: https://docs.sentry.io/platforms/python/integrations/pure_eval Install the Sentry Python SDK with the pure_eval extra via pip. This also installs pure_eval, executing, and asttokens. ```bash pip install "sentry-sdk[pure_eval]" ``` -------------------------------- ### Run a Pydantic AI agent with Sentry integration Source: https://docs.sentry.io/platforms/python/agent-tracing/pydantic-ai Use this example to verify the Sentry Pydantic AI integration. It initializes Sentry with the PydanticAIIntegration, defines a customer support agent using Pydantic AI, and runs it to produce trace data that should appear in the Agents Dashboard. The code includes a tool for order lookup and sets send_default_pii to True to capture LLM and tool inputs/outputs. ```python import asyncio import sentry_sdk from sentry_sdk.integrations.pydantic_ai import PydanticAIIntegration from sentry_sdk.integrations.openai import OpenAIIntegration from pydantic_ai import Agent, RunContext from pydantic import BaseModel class SupportResponse(BaseModel): message: str sentiment: str requires_escalation: bool support_agent = Agent( 'openai:gpt-4o-mini', name="Customer Support Agent", system_prompt=( "You are a helpful customer support agent. Analyze customer inquiries, " "provide helpful responses, and determine if escalation is needed. " "If the customer mentions an order number, use the lookup tool to get details." ), result_type=SupportResponse, ) @support_agent.tool async def lookup_order(ctx: RunContext[None], order_id: str) -> dict: """Look up order details by order ID. Args: ctx: The context object. order_id: The order identifier. Returns: Order details including status and tracking. """ # In a real application, this would query a database return { "order_id": order_id, "status": "shipped", "tracking_number": "1Z999AA10123456784", "estimated_delivery": "2024-03-15" } async def main() -> None: sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", traces_sample_rate=1.0, # Add data like LLM and tool inputs/outputs; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, integrations=[ PydanticAIIntegration(), ] ) result = await support_agent.run( "Hi, I'm wondering about my order #ORD-12345. When will it arrive?" ) print(result.data) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start a span with a context manager in Python Source: https://docs.sentry.io/platforms/python/tracing/span-lifecycle Use sentry_sdk.start_span with a context manager to automatically start and end a span. The span starts when entering the 'with' block and ends when exiting it. This is the recommended approach for most scenarios. ```python import sentry_sdk # Start a span for a task with sentry_sdk.start_span(op="task", name="Create User"): # Your code here # The span will automatically end when exiting this block user = create_user(email="user@example.com") send_welcome_email(user) # The span automatically ends here when the 'with' block exits ``` -------------------------------- ### Configure Sanic with Sentry SDK Source: https://docs.sentry.io/platforms/python/integrations/sanic Recommended setup for the Sanic integration. Initializes the Sentry SDK within a `before_server_start` listener and explicitly adds the `AsyncioIntegration` to ensure background task errors are reported. Includes options for tracing and profiling. ```python from sanic import Sanic import sentry_sdk from sentry_sdk.integrations.asyncio import AsyncioIntegration app = Sanic(__main__) @app.listener("before_server_start") async def init_sentry(_): sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", # Add data like request headers and IP for users; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # ___PRODUCT_OPTION_START___ performance # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. traces_sample_rate=1.0, # ___PRODUCT_OPTION_END___ performance # ___PRODUCT_OPTION_START___ profiling # To collect profiles for all profile sessions, # set `profile_session_sample_rate` to 1.0. profile_session_sample_rate=1.0, # Profiles will be automatically collected while # there is an active span. profile_lifecycle="trace", # ___PRODUCT_OPTION_END___ profiling integrations=[AsyncioIntegration()], ) ``` -------------------------------- ### Configure serverless_function decorator Source: https://docs.sentry.io/platforms/python/integrations/serverless Configure the generic serverless integration by initializing the SDK and decorating each function that might throw errors with `serverless_function`. The example includes optional tracing and profiling settings; adjust the DSN and feature options as needed. ```python import sentry_sdk from sentry_sdk.integrations.serverless import serverless_function sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", # Add data like request headers and IP for users, if applicable; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # ___PRODUCT_OPTION_START___ performance # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. traces_sample_rate=1.0, # ___PRODUCT_OPTION_END___ performance # ___PRODUCT_OPTION_START___ profiling # To collect profiles for all profile sessions, # set `profile_session_sample_rate` to 1.0. profile_session_sample_rate=1.0, # Profiles will be automatically collected while # there is an active span. profile_lifecycle="trace", # ___PRODUCT_OPTION_END___ profiling ) @serverless_function def my_function(...): ... ``` -------------------------------- ### Install sentry-sdk with OpenTelemetry Source: https://docs.sentry.io/platforms/python/tracing/instrumentation/opentelemetry Install the Sentry Python SDK with OpenTelemetry support. Requires opentelemetry-distro version 0.350b0 or higher. ```bash pip install "sentry-sdk[opentelemetry]" ``` -------------------------------- ### Configure RayIntegration with sentry_sdk.init() Source: https://docs.sentry.io/platforms/python/integrations/ray Configure Sentry with the Ray integration. Call sentry_sdk.init() before ray.init() and set worker_process_setup_hook to initialize Sentry inside Ray worker processes. ```python import ray import sentry_sdk from sentry_sdk.integrations.ray import RayIntegration def init_sentry(): sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", # Add data like request headers and IP for users, if applicable; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # ___PRODUCT_OPTION_START___ performance # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. traces_sample_rate=1.0, # ___PRODUCT_OPTION_END___ performance # ___PRODUCT_OPTION_START___ profiling # To collect profiles for all profile sessions, # set `profile_session_sample_rate` to 1.0. profile_session_sample_rate=1.0, # Profiles will be automatically collected while # there is an active span. profile_lifecycle="trace", # ___PRODUCT_OPTION_END___ profiling integrations=[ RayIntegration(), ], ) init_sentry() ray.init( runtime_env={"worker_process_setup_hook": init_sentry}, ) ``` -------------------------------- ### Initialize Sentry SDK for logs Source: https://docs.sentry.io/platforms/python/logs Initialize the Sentry SDK. Logging is enabled by default, so no extra configuration is needed. ```python sentry_sdk.init( dsn="https://@o.ingest.sentry.io/", ) ```