Configure custom buckets for histograms
This page describes how to configure custom buckets for histograms. The default buckets for histograms are as follows:
- [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10]
The unit of the above buckets is seconds.
You can configure custom buckets for histograms by adding a view for the metric and specifying the buckets in the view. This needs to be done at the time the meter provider is initialized. The following example shows how to do this:
from opentelemetry.metrics import set_meter_provider
from opentelemetry.sdk.metrics import MeterProvider, Histogram
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
# the following boundaries are in milliseconds
# change this to the desired boundaries based on your metric and how you record the metric
# i.e in your code if you record the metric in milliseconds, then the boundaries should be in milliseconds
# if you record the metric in seconds, then the boundaries should be in seconds
boundaries = [0.0,100.0,250.0,500.0,750.0,1000.0,2500.0,5000.0,7500.0,10000.0,15000.0,20000.0,30000.0,45000.0,60000.0]
# the following view updates the bucket boundaries for all histogram metrics
custom_buckets_for_all_histograms = View(
instrument_type=Histogram,
aggregation=ExplicitBucketHistogramAggregation(boundaries=boundaries)
)
# the following view updates the bucket boundaries for a histogram metric with name "my-histogram"
custom_buckets_for_specific_metric = View(
instrument_type="my-histogram",
aggregation=ExplicitBucketHistogramAggregation(boundaries=boundaries)
)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(),
)
set_meter_provider(MeterProvider(
metric_readers=[reader],
views=[custom_buckets_for_all_histograms]
))