Sending Metrics (SDK)

Using Python SDK

In case you are looking to use the new metrics feature directly from the Python SDK you can do it as follows.

First, you have to use at least the 1.38.0 version of the sentry-python SDK and add that as your dependency. For example:

Copied
sentry-sdk @ 1.38.0

Once the SDK is installed you have to add experimental flag into your SDK init:

Copied
import sentry_sdk

sentry_sdk.init(
    ...
    _experiments={
        # Turns on the metrics module (required)
        "enable_metrics": True,
        # Enables sending of code locations for metrics (recommended)
        "metric_code_locations": True,
    },
)

Ensure you have feature flags for both ingestion and UI enabled.

Then you can use the metrics method as follows:

Copied
from sentry_sdk import metrics

# Emit a counter
metrics.incr(
    key="my_counter",
    value=2,
    tags=tags,
)

# Emit a distribution
metrics.distribution(
    key="my_distribution",
    value=15.0,
    tags=tags,
    # You can also specify a unit if you want
    unit="second",
)

# Emit a set
metrics.set(
    key="my_set",
    value="john",
    tags=tags,
)

# Emit a gauge
metrics.gauge(
    key="my_gauge",
    value=10,
    tags=tags,
)

If you want to measure how much time a specific piece of code takes, you can use:

Copied
from sentry_sdk import metrics

# Emit a distribution metric of the execution time of the function.
with metrics.timing("my_function"):
    pass

@metrics.timing("my_function")
def my_function():
    pass

Units Support

The following units are supported out of the box (but the system also allows you to pass your own unit if you need):

Copied
"nanosecond",
"microsecond",
"millisecond",
"second",
"minute",
"hour",
"day",
"week",
"bit",
"byte",
"kilobyte",
"kibibyte",
"megabyte",
"mebibyte",
"gigabyte",
"gibibyte",
"terabyte",
"tebibyte",
"petabyte",
"pebibyte",
"exabyte",
"exbibyte",
"ratio",
"percent",
"none"

Automatic Tags Extraction

Since DDM has the goal of being tightly integrated into Sentry, the sentry-python implementation already automatically adds the following tags to your metric:

  • transaction
  • release
  • environment

As we will see later on, these special tags are recognized by the DDM UI and will prompt you with helpful actions.

You can edit this page on GitHub.