Metrics over OTLP
The library has no metrics API of its own.
An opentelemetry-otlp MetricExporter is pointed at the Telemetry endpoint and authenticated with GcpAuthInterceptor, which attaches and refreshes the Google credentials of each request.
The otlp feature enables the tonic transport and TLS of opentelemetry-otlp; enable its metrics feature in your own Cargo.toml:
[dependencies]
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["metrics"] }
let exporter = MetricExporter::builder()
.with_tonic()
.with_endpoint("https://telemetry.googleapis.com")
.with_tls_config(ClientTlsConfig::new().with_enabled_roots())
.with_interceptor(GcpAuthInterceptor::from_adc().await?)
.build()?;
let meter_provider = SdkMeterProvider::builder()
.with_periodic_exporter(exporter)
.with_resource(
opentelemetry_sdk::Resource::builder()
.with_service_name("metrics-otlp-example")
.with_attribute(KeyValue::new(
"service.instance.id",
"metrics-otlp-example-1",
))
.with_attribute(KeyValue::new("cloud.region", "europe-west1"))
.with_attribute(KeyValue::new("gcp.project_id", google_project_id))
.build(),
)
.build();
GcpAuthInterceptor::from_adc() uses the Application Default Credentials with the cloud-platform scope.
GcpAuthInterceptor::new takes other GoogleAuthHeaders, which gcloud_observability::otlp re-exports.
See Authentication for how the headers are kept current.
Resource attributes
The Telemetry API places each metric by the resource it comes from, and refuses a resource that misses one of these with InvalidArgument:
gcp.project_id: the project;service.nameandservice.instance.id: the task;cloud.region, orcloud.availability_zone: where it ran. The value cannot beglobal.
Metric data is stored on a regional endpoint only when its location label matches the region or a zone of it, see OTLP exporter.
Call meter_provider.shutdown() before the process ends: it exports the metrics collected so far and stops the periodic reader.
Full example available here.