---
title: "Custom Instrumentation"
description: "Learn how to capture performance data on any action in your app using the Sentry Python SDK."
url: https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation/
---

# Custom Instrumentation for Python

The Sentry SDK for Python does a very good job of auto instrumenting your application. If you use one of the popular frameworks, we've got you covered because well-known operations like HTTP calls and database queries will be instrumented out of the box. The Sentry SDK will also check your installed Python packages and auto-enable the matching SDK integrations. If you want to enable tracing in a piece of code that performs some other operations, add the `@sentry_sdk.trace` decorator.

The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. If you use [stream mode](https://docs.sentry.io/platforms/python/tracing/streamed-spans.md) in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`.

##### Changed in 2.15.0

The parameter `name` in `start_span()` used to be called `description`. In version 2.15.0 `description` was deprecated and from 2.15.0 on, only `name` should be used. `description` will be removed in `3.0.0`.

## [Add a Service Span](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#add-a-service-span)

Adding service spans (transactions in SDK `2.x`) will allow you to instrument and capture certain regions of your code.

If you're using one of Sentry's SDK integrations, service spans will be created for you automatically.

The following example creates a service span for an expensive operation (in this case, `eat_pizza`), and then sends the result to Sentry:

```python
import sentry_sdk

def eat_slice(slice):
    ...

def eat_pizza(pizza):
    with sentry_sdk.start_span(
        name="Eat Pizza",
        attributes={"sentry.op": "task"},
        # set parent span to None to create service span
        parent_span=None,
    ):
        while pizza.slices > 0:
            span = sentry_sdk.start_span(name="Eat Slice")
            eat_slice(pizza.slices.pop())
            span.end()
```

*Other available variations of the above snippet: SDK 2.x*

The [API reference](https://getsentry.github.io/sentry-python/api.html#performance-monitoring) documents `start_span`, along with its parameters.

`sentry_sdk.start_span()` can, but doesn't have to be, used as a context manager. If you don't use it as a context manager, make sure to call `span.end()` to finish the span.

In SDK `2.x`, `sentry_sdk.start_transaction()` is meant to be used as a context manager. This ensures that the transaction will be properly set as active and any spans created within will be attached to it.

## [Add Spans to a Service Span](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#add-spans-to-a-service-span)

If you want to have more fine-grained performance monitoring, you can add child spans to your service span, which can be done by either:

* Using a context manager
* Using a decorator (this works on sync and async functions)
* Manually starting and finishing a span

Calling `sentry_sdk.start_span()` will find the current active span and attach the new span to it.

### [Using a Context Manager](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#using-a-context-manager)

```python
import sentry_sdk

def eat_slice(slice):
    ...

def eat_pizza(pizza):
    with sentry_sdk.start_span(
        name="Eat Pizza",
        attributes={"sentry.op": "task"},
        parent_span=None,
    ):
        while pizza.slices > 0:
            with sentry_sdk.start_span(name="Eat Slice"):
                eat_slice(pizza.slices.pop())
```

*Other available variations of the above snippet: SDK 2.x*

### [Using a Decorator](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#using-a-decorator)

```python
import sentry_sdk

@sentry_sdk.trace
def eat_slice(slice):
    ...

def eat_pizza(pizza):
    with sentry_sdk.start_span(
        name="Eat Pizza",
        attributes={"sentry.op": "task"},
        parent_span=None,
    ):
        while pizza.slices > 0:
            eat_slice(pizza.slices.pop())
```

*Other available variations of the above snippet: SDK 2.x*

See the [@sentry\_sdk.trace decoration section](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#sentry_sdktrace-decorator) below for more details.

##### Static & class methods

When tracing a static or class method, you **must** add the `@sentry_sdk.trace` decorator **after** the `@staticmethod` or `@classmethod` decorator (i.e., **closer** to the function definition). Otherwise, your function will break.

### [Manually Starting and Finishing a Span](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#manually-starting-and-finishing-a-span)

```python
import sentry_sdk

def eat_slice(slice):
    ...

def eat_pizza(pizza):
    with sentry_sdk.start_span(
        name="Eat Pizza",
        attributes={"sentry.op": "task"},
        parent_span=None,
    ):
        while pizza.slices > 0:
            span = sentry_sdk.start_span(name="Eat Slice")
            eat_slice(pizza.slices.pop())
            span.end()
```

*Other available variations of the above snippet: SDK 2.x*

When you create your span manually, make sure to call `span.end()` (in SDK `2.x`, `span.finish()`) after the block of code you want to wrap in a span to finish the span. If you do not finish the span it will not be sent to Sentry.

## [Nested Spans](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#nested-spans)

Spans can be nested to form a span tree. If you'd like to learn more, read our [distributed tracing](https://docs.sentry.io/concepts/key-terms/tracing/distributed-tracing.md) documentation.

### [Using a Context Manager](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#using-a-context-manager-1)

```python
import sentry_sdk

def chew():
    ...

def eat_slice(slice):
    with sentry_sdk.start_span(name="Eat Slice"):
        with sentry_sdk.start_span(name="Chew"):
            chew()
```

*Other available variations of the above snippet: SDK 2.x*

### [Using a Decorator](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#using-a-decorator-1)

```python
import sentry_sdk

@sentry_sdk.trace
def chew():
    ...

@sentry_sdk.trace
def eat_slice(slice):
    chew()
```

*Other available variations of the above snippet: SDK 2.x*

See the [@sentry\_sdk.trace decoration section](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#sentry_sdktrace-decorator) below for more details.

### [Manually Starting and Finishing](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#manually-starting-and-finishing)

```python
import sentry_sdk

def chew():
    ...

def eat_slice(slice):
    parent_span = sentry_sdk.start_span(name="Eat Slice")

    # pass the parent span via `parent_span` to create a child span
    child_span = sentry_sdk.start_span(name="Chew", parent_span=parent_span)
    chew()
    child_span.end()

    parent_span.end()
```

*Other available variations of the above snippet: SDK 2.x*

The span will become the child of the currently active span. Alternatively, you can pass the parent span explicitly via `parent_span` when starting the child (as shown in the example above). See the [API reference](https://getsentry.github.io/sentry-python/api.html#sentry_sdk.api.start_span) for more details.

In SDK `2.x`, there is also a specialized `start_child()` method. The parameters of `start_span()` and `start_child()` are the same.

When you create your span manually, make sure to call `span.end()` (in SDK `2.x`, `span.finish()`) after the block of code you want to wrap in a span to finish the span. If you do not finish the span it will not be sent to Sentry.

### [Sibling Spans](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#sibling-spans)

In SDK `2.x`, only available in stream mode.

A span normally attaches to whatever span is currently active. To control parentage explicitly, for example to make a span a sibling instead of a child, pass `parent_span` directly:

```python
import sentry_sdk

def eat_slice(slice):
    ...

def chew():
    ...

def eat_pizza(pizza):
    with sentry_sdk.start_span(name="Eat Pizza") as pizza_span:
        with sentry_sdk.start_span(name="Eat Slice"):
            with sentry_sdk.start_span(name="Chew", parent_span=pizza_span):
                # "Chew" is a sibling of "Eat Slice", not its child
                chew()
            eat_slice(pizza.slices.pop())
```

## [@sentry\_sdk.trace decorator](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#sentry_sdktrace-decorator)

The `@sentry_sdk.trace` decorator accepts `name`, `attributes`, and `active` to customize your spans. Note that there's no `op` parameter; set the operation as the `sentry.op` key in `attributes` instead. Attribute values can only be primitive types (like `int`, `float`, `bool`, `str`) or a list of those types without mixing types.

In SDK `2.x`, the decorator accepts `op`, `name`, and `attributes`.

##### Static & class methods

When tracing a static or class method, you **must** add the decorator **after** the `@staticmethod` or `@classmethod` decorator (i.e., **closer** to the function definition). Otherwise, your function will break.

```python
import sentry_sdk

@sentry_sdk.trace(name="Paul", attributes={"sentry.op": "my_op", "x": True})
def my_function(i):
    ...

@sentry_sdk.trace
def root_function():
    for i in range(3):
        my_function(i)

root_function()
```

*Other available variations of the above snippet: SDK 2.x*

The code above will customize the `my_function` spans like this:

```mermaid
gantt
    dateFormat DD
    todayMarker off
    axisFormat %
    SPAN(op=function, name=root_function)   :a1, 01, 7d
    SPAN(op=my_op, name=Paul, x=True)    :a2, 02, 2d
    SPAN(op=my_op, name=Paul, x=True)    :a3, 04, 2d
    SPAN(op=my_op, name=Paul, x=True)    :a4, 06, 2d
```

### [Span Templates](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#span-templates)

Only available in SDK versions prior to `3.0`.

In the `@sentry_sdk.trace` decorator you can also specify a `template`. This helps create spans that follow a certain template. Currently this is only available for spans that are created for the [agents instrumentation](https://docs.sentry.io/platforms/python/agent-tracing/manual-instrumentation.md) of Sentry.

Available templates are `AI_AGENT`, `AI_TOOL`, and `AI_CHAT`.

```python
 import sentry_sdk
 from sentry_sdk.consts import SPANTEMPLATE

+@sentry_sdk.trace(template=SPANTEMPLATE.AI_AGENT)
 def my_function(i):
     ...

 @sentry_sdk.trace
 def root_function():
     for i in range(3):
         my_function(i)

 root_function()
```

This will treat `my_function` as an agent and will create the following span tree that is compatible with the [OpenTelemetry Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/) and the Sentry conventions for [agents instrumentation](https://docs.sentry.io/platforms/python/agent-tracing/manual-instrumentation.md). Depending on the template, there will also be a couple of attributes set by default, but those are omitted in the graph below for readability reasons:

```mermaid
gantt
    dateFormat DD
    todayMarker off
    axisFormat %
    SPAN(op=function, name=root_function)   :a1, 01, 7d
    SPAN(op=gen_ai.invoke_agent, name="invoke_agent my_function")    :a2, 02, 2d
    SPAN(op=gen_ai.invoke_agent, name="invoke_agent my_function")    :a3, 04, 2d
    SPAN(op=gen_ai.invoke_agent, name="invoke_agent my_function")    :a4, 06, 2d
```

For the span attributes that are set for the different available templates, see the agents instrumentation documentation:

* `SPANTEMPLATE.AI_AGENT` -> [Invoke Agent Span](https://docs.sentry.io/platforms/python/agent-tracing/manual-instrumentation.md#invoke-agent-span)
* `SPANTEMPLATE.AI_CHAT` -> [AI Request span](https://docs.sentry.io/platforms/python/agent-tracing/manual-instrumentation.md#ai-request-span)
* `SPANTEMPLATE.AI_TOOL` -> [Execute Tool Span](https://docs.sentry.io/platforms/python/agent-tracing/manual-instrumentation.md#execute-tool-span)

Currently it is not possible to define custom span templates.

## [Define Span Creation in a Central Place](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#define-span-creation-in-a-central-place)

To avoid having custom performance instrumentation code scattered all over your code base, pass a parameter `functions_to_trace` to your `sentry_sdk.init()` call.

```python
import sentry_sdk

functions_to_trace = [
    {"qualified_name": "myrootmodule.eat_slice"},
    {"qualified_name": "myrootmodule.swallow"},
    {"qualified_name": "myrootmodule.chew"},
    {"qualified_name": "myrootmodule.someothermodule.another.some_function"},
    {"qualified_name": "myrootmodule.SomePizzaClass.some_method"},
]

sentry_sdk.init(
    dsn="https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
    functions_to_trace=functions_to_trace,
)
```

Now, whenever a function specified in `functions_to_trace` will be executed, a span will be created and attached as a child to the currently running span.

##### Important

To enable performance monitoring for the functions specified in `functions_to_trace`, the SDK needs to load the function modules. Be aware, there may be code being executed in modules during module loading. To avoid this, use the method described above to trace your functions.

## [Accessing the Current Transaction](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#accessing-the-current-transaction)

Only available in SDK versions prior to `3.0`. Use [`sentry_sdk.get_current_span()`](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#accessing-the-current-span) instead.

The `sentry_sdk.get_current_scope().transaction` property returns the active transaction or `None` if no transaction is active. You can use this property to modify data on the transaction.

```python
import sentry_sdk

def eat_pizza(pizza):
    transaction = sentry_sdk.get_current_scope().transaction

    if transaction is not None:
        transaction.set_tag("num_of_slices", len(pizza.slices))

    while pizza.slices > 0:
        eat_slice(pizza.slices.pop())
```

## [Accessing the Current Span](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#accessing-the-current-span)

To change data in the current span, use `sentry_sdk.get_current_span()`. This function will return a span if there's one running, otherwise it will return `None`.

In this example, we'll set custom data in the span created by the `@sentry_sdk.trace` decorator.

```python
import sentry_sdk

@sentry_sdk.trace
def eat_slice(slice):
    span = sentry_sdk.get_current_span()

    if span is not None:
        span.set_attribute("slice_id", slice.id)
```

*Other available variations of the above snippet: SDK 2.x*

## [Adding Span Attributes](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#adding-span-attributes)

Span attributes describe an operation in a trace: which provider handled a request, which fallback ran, or what outcome it produced. When investigating a slow checkout, compare charge spans by `payment.provider` and open an outlier trace to see what happened. The span already records its duration, so you don't need a separate duration attribute.

Add attributes to the span for the operation they describe, rather than creating an empty span just to hold attributes. Use `set_attribute()` or `set_attributes()` (in SDK `2.x`, `set_data()`). Values can be strings, numbers, booleans, or arrays containing only one of these types. For example, record what happens during a payment charge:

```python
with sentry_sdk.start_span(
    name="Charge payment provider",
    attributes={"sentry.op": "payment.charge", "payment.provider": provider.name},
) as span:
    result = provider.charge(order)
    span.set_attributes({
        "payment.retry_count": result.retry_count,
        "payment.outcome": result.outcome,
    })
```

*Other available variations of the above snippet: SDK 2.x*

Choose consistent names and values you can filter or group by. Avoid sensitive values such as raw search terms and payment details. In [Trace Explorer](https://docs.sentry.io/product/trace-explorer.md), filter on `span.op:payment.charge`, compare `span.duration` by `payment.provider`, and open a slow sample to inspect retries and other bottlenecks.

Attributes belong to sampled traces. For counters, gauges, or distributions independent of trace sampling, such as failed checkout counts or queue depth, use [Application Metrics](https://docs.sentry.io/product/metrics.md) instead. To add shared context to every span, use the appropriate callback for your tracing mode:

How you add data to every span depends on your SDK version:

```python
import sentry_sdk

def before_send_span(span, hint):
    # Runs once per span, as it's flushed.
    if "attributes" not in span:
        span["attributes"] = {}
    span["attributes"].update({
        "deployment.cell": "us-west-2a",
        "config.variant": "new-search",
    })
    return span

sentry_sdk.init(
    # ...
    before_send_span=before_send_span,
)
```

*Other available variations of the above snippet: SDK 2.x*

`before_send_span` can only modify span data and you cannot use it to drop spans. See [Dropping Spans](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#dropping-spans) below.

## [Dropping Spans](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation.md#dropping-spans)

In SDK versions prior to `3.0`, `ignore_spans` is only available in stream mode.

You can prevent specific spans from being created using `ignore_spans`. It evaluates rules at span start, which can be strings, compiled regexes, or dictionaries with `name` and/or `attributes` conditions. If the dropped span is a service span, its children are dropped too. If it's a child span, only that span is dropped and its children are reparented to the nearest ancestor.

```python
import re
import sentry_sdk

sentry_sdk.init(
    ignore_spans=[
        # String match against span name
        "/health",

        # Regex match against span name
        re.compile(r"/flow/.*"),

        # Match by attributes (all must match)
        {
            "attributes": {
                "service.id": "15def9a",
                "flow.pipeline": "legacy",
            }
        },

        # Match by name and attributes
        {
            "name": re.compile(r"/flow/.*"),
            "attributes": {
                "service.id": re.compile(r".*\.facade"),
            },
        },
    ],
)
```

## Pages in this section

- [Instrument MCP Servers](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation/mcp-module.md)
- [Instrument Caches](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation/caches-module.md)
- [Instrument HTTP Requests](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation/requests-module.md)
- [Instrument Queues](https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation/queues-module.md)
