prometheus.go
Overview
The [prometheus.go](/projects/291/69100) file defines a metrics instrumentation layer for monitoring an application using Prometheus, a popular open-source monitoring and alerting toolkit. It encapsulates the creation, registration, and organization of Prometheus metrics, specifically tailored for HTTP request tracking and WebSocket client connection counts.
The primary purpose of this file is to provide a reusable and extensible Prometheus metrics registry with pre-defined metrics that track:
The count of HTTP requests, labeled by HTTP method, route, and response status code.
The duration of HTTP requests, also labeled by method, route, and status code.
The number of active WebSocket client connections.
This file is foundational in enabling observability for the system by exposing meaningful metrics that can be scraped by Prometheus servers and visualized or alerted on via tools like Grafana.
Package and Imports
Package:
metrics— Indicates this file is part of a metrics collection subsystem.Imports:
reflect— Used for iterating over the fields of theMetricsstruct to register them dynamically.github.com/prometheus/client_golang/prometheus — The official Prometheus client library for Go.
github.com/prometheus/client_golang/prometheus/collectors — Provides default collectors for Go runtime and process metrics.
Types
Prometheus
type Prometheus struct {
Registry *prometheus.Registry
Metrics Metrics
}
**Description:** The `Prometheus` struct is a container that holds a Prometheus registry (`prometheus.Registry`) and a collection of application-specific metrics (`Metrics`). This struct provides a centralized object to access all registered metrics and the registry itself.
**Fields:**
Registry— Pointer to the Prometheus registry that holds all metric collectors.Metrics— An instance of theMetricsstruct containing custom application metrics.
Metrics
type Metrics struct {
HTTPRequestCounter *prometheus.CounterVec
HTTPRequestDurationSeconds *prometheus.HistogramVec
WebsocketCount prometheus.Gauge
}
**Description:** Defines specific Prometheus metric collectors used by the application.
**Fields:**
HTTPRequestCounterType:
*prometheus.CounterVecTracks the count of HTTP requests, partitioned by labels "method", "route", and "statusCode".
HTTPRequestDurationSecondsType:
*prometheus.HistogramVecMeasures the duration of HTTP requests in seconds, partitioned by the same labels.
WebsocketCountType:
prometheus.GaugeRepresents the current number of active WebSocket client connections.
Labels
type Labels = prometheus.Labels
**Description:** Type alias for `prometheus.Labels`, which is a map of string keys to string values used to label metrics.
Functions
NewPrometheus
func NewPrometheus(coinstack string) *Prometheus
**Description:** Creates a new `Prometheus` instance initialized with a fresh registry and registers default Go runtime and process collectors along with custom application metrics.
**Parameters:**
coinstack(string): A constant label value used to annotate all metrics with the specific "coinstack" (likely the blockchain stack or application context).
**Returns:**
Pointer to a fully initialized
Prometheusstruct.
**Implementation Details:**
Creates a new Prometheus registry.
Registers default collectors for Go runtime metrics and process metrics.
Defines three application-specific metrics (
HTTPRequestCounter,HTTPRequestDurationSeconds,WebsocketCount) with the providedcoinstacklabel.Uses reflection to iterate over all fields in the
Metricsstruct and registers each metric collector with the registry.Returns the assembled
Prometheusstruct.
**Example Usage:**
p := NewPrometheus("bitcoin")
// Now p.Registry can be used to expose metrics endpoint,
// and p.Metrics.HTTPRequestCounter can be incremented in HTTP handlers.
Important Implementation Details
Dynamic Registration via Reflection:
The use ofreflect.ValueOf(metrics)allows automatic registration of any new Prometheus collectors added to theMetricsstruct without needing to manually register each one. This pattern reduces boilerplate and potential errors in metrics registration.ConstLabels:
Each metric includes a constant label"coinstack"which provides context about the environment or blockchain stack the metrics belong to. This is useful for filtering or grouping metrics when monitoring multiple deployments or services.Buckets for Histogram:
The HTTP request duration histogram uses a custom bucket range tailored for typical HTTP request latencies, ranging from 5ms to 10 seconds. This allows detailed latency distribution analysis.
Interaction with the System
This file likely sits in the metrics or monitoring subsystem of the application.
The returned
Prometheusstruct fromNewPrometheusis used by HTTP servers or WebSocket handlers to instrument metrics:HTTP handlers increment
HTTPRequestCounterand observe durations onHTTPRequestDurationSeconds.WebSocket connection handlers update
WebsocketCountgauge to reflect active client connections.
The
Registryis exposed to an HTTP endpoint (outside this file) to allow Prometheus to scrape metrics.The inclusion of Go runtime and process collectors ensures standard runtime metrics are also available alongside custom metrics.
Mermaid Diagram
classDiagram
class Prometheus {
+Registry *prometheus.Registry
+Metrics Metrics
}
class Metrics {
+HTTPRequestCounter *prometheus.CounterVec
+HTTPRequestDurationSeconds *prometheus.HistogramVec
+WebsocketCount prometheus.Gauge
}
Prometheus "1" *-- "1" Metrics : contains
Summary
The [prometheus.go](/projects/291/69100) file provides a clean, extensible Prometheus instrumentation setup for HTTP and WebSocket metrics. It encapsulates metric creation, registration, and organization, enabling other parts of the system to easily integrate metrics collection with minimal boilerplate. The use of reflection and constant labels ensures maintainability and contextual richness for monitoring data. This file forms a critical part of the system's observability infrastructure.