From 70df4ed50f1ab3e0a1e230f64f9d463e7c379267 Mon Sep 17 00:00:00 2001 From: Richard Towers Date: Wed, 15 Jan 2025 15:55:18 +0000 Subject: [PATCH] GovukPrometheus - custom labels from rack env Apps can use request.env['govuk.prometheus_labels'] to specify custom labels for prometheus. For example, and app might do: prometheus_labels = request.env.fetch('govuk.prometheus_labels', {}) request.env['govuk.prometheus_labels'] = prometheus_labels.merge( document_type: @content_item.document_type, schema_name: @content_item.schema_name, ) To set the document type / schema name as custom labels (which is useful for the apps where this isn't obvious based on controller / action, like government-frontend) Testing locally, this results in metrics like: http_request_duration_seconds_count{action="show",controller="content_items",document_type="answer",schema_name="answer"} 1 Care does need to be taken with the cardinality of prometheus labels (i.e. there shouldn't be too many different combinations of labels), but things like document_type are useful and shouldn't increase cardinality too much. --- .../govuk_prometheus_exporter.rb | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/govuk_app_config/govuk_prometheus_exporter.rb b/lib/govuk_app_config/govuk_prometheus_exporter.rb index 424a1fa..24b84fd 100644 --- a/lib/govuk_app_config/govuk_prometheus_exporter.rb +++ b/lib/govuk_app_config/govuk_prometheus_exporter.rb @@ -4,13 +4,13 @@ require "prometheus_exporter/middleware" module GovukPrometheusExporter - # - # See https://github.com/discourse/prometheus_exporter/pull/293 - # - # RailsMiddleware can be removed and replaced with the default middleware if - # that PR is merged / released - # class RailsMiddleware < PrometheusExporter::Middleware + # + # See https://github.com/discourse/prometheus_exporter/pull/293 + # + # default_labels can be removed and fall through to the base method if + # that PR is merged / released + # def default_labels(env, _result) controller_instance = env["action_controller.instance"] action = controller = nil @@ -28,6 +28,10 @@ def default_labels(env, _result) controller: controller || "other", } end + + def custom_labels(env) + env.fetch('govuk.prometheus_labels', {}) + end end class SinatraMiddleware < PrometheusExporter::Middleware @@ -39,6 +43,10 @@ def default_labels(_env, _result) # the application / pod and don't provide any other labels {} end + + def custom_labels(env) + env.fetch('govuk.prometheus_labels', {}) + end end def self.should_configure