Skip to content

Commit

Permalink
GovukPrometheus - custom labels from rack env
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
richardTowers committed Jan 15, 2025
1 parent 90124a6 commit 70df4ed
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions lib/govuk_app_config/govuk_prometheus_exporter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 70df4ed

Please sign in to comment.