Sending Metrics (Abstraction)

Sentry Metrics Abstraction

In order to make metrics collection uniform across the entire sentry codebase, we have an abstraction known as MetricsBackend which exposes metrics collection with three methods.

  • incr → emits a counter metric.
  • timing → emits a distribution metric (with the second unit on Sentry metrics).
  • gauge → emits a gauge metric (temporarily emits a counter, until the infra work is done).

Each method has three main parameters:

  • key → the name that uniquely identifies the metric. You will use the name to specify the metric when you want to plot it.
  • value → the value of the value. You will plot the value of the metric.
  • tags → the tags of the metric. You will use the tags to attach metadata to the metric, which can be helpful for aggregations.

To learn more about MetricsBackend, visit Internal Metrics.

Using the MetricsBackend

To use the metrics backend you will first have to import it:

Copied
from sentry.utils import metrics

Once imported, you can start emitting metrics:

Copied
# Emit a counter.
metrics.incr(
	"counter_name",
	tags={"platform": platform}
)

# Emit a distribution.
metrics.timing(
	"distribution_name",
	100,
	tags={"user_segment": user_segment}
)

# Emit a gauge.
metrics.gauge(
	"gauge_name",
	10,
	tags={"nation": nation}
)

# Emit a gauge.
metrics.distribution(
	"gauge_name",
	10,
	tags={"nation": nation},
	unit="second",
)

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

Copied
# Emit a distribution metric of the execution time of the function.
with metrics.timer("my_func_speed"):
	my_func()

Details about the MetricsBackend

The current implementation of the MetricsBackend is known as CompositExperimentalMetricsBackend. It's a backend that forwards your metrics to both Datadog and Sentry. For this reason, you will be able to see your metrics on both platforms, even though the end goal is to use our own metrics product when it is mature enough. More details here.

Keep in mind that due to scale implications, we might sample the metrics sent to Sentry. This is only temporary but it means that for now if you need high-fidelity metrics, we still suggest you refer to Datadog.

You can edit this page on GitHub.