Skip to main content

Overview

The prometheus middleware exposes metrics in Prometheus format, enabling integration with Prometheus monitoring systems. Use it when you need:
  • Prometheus monitoring
  • Grafana dashboards
  • AlertManager integration

Installation

Quick Start

Configuration

Options

Examples

Basic Setup

With Namespace

Skip Metrics Endpoint

Custom Labels

Default Metrics

API Reference

Functions

Prometheus Config

Technical Details

Implementation Architecture

The Prometheus middleware is implemented with the following key components:
  • Metrics Collector: A thread-safe Metrics struct that maintains multiple metric types
  • Custom Histogram: Lightweight histogram implementation for request duration and size tracking
  • Response Writer Wrapper: Custom responseWriter to capture HTTP status codes and response sizes
  • Atomic Operations: Uses sync/atomic for concurrent request counting and active request tracking

Core Metrics

The middleware collects four primary metric types:
  1. Request Counter (http_requests_total): Total number of HTTP requests with labels for method, path, and status
  2. Request Duration Histogram (http_request_duration_seconds): Request latency distribution in seconds
  3. Request Size Histogram (http_request_size_bytes): HTTP request size distribution with fixed buckets [100, 1000, 10000, 100000, 1000000]
  4. Response Size Histogram (http_response_size_bytes): HTTP response size distribution with fixed buckets [100, 1000, 10000, 100000, 1000000]
  5. Active Requests Gauge (http_requests_active): Current number of in-flight requests

Label Structure

Metrics include the following labels:
  • method: HTTP method (GET, POST, etc.)
  • path: Request path
  • status: HTTP status code (for counter and duration metrics)

Default Histogram Buckets

Request duration uses the following default buckets (in seconds):

Thread Safety

  • All metric recording operations are thread-safe using sync.RWMutex and atomic operations
  • Histogram observations are protected by individual mutex locks
  • Request counters use atomic increment operations for optimal performance

Metric Naming

Full metric names follow the pattern:
  • With namespace and subsystem: <namespace>_<subsystem>_<metric_name>
  • With namespace only: <namespace>_<metric_name>
  • With subsystem only: <subsystem>_<metric_name>
  • Default: <metric_name>

Best Practices

  • Use consistent naming
  • Avoid high cardinality labels
  • Skip health/metrics endpoints
  • Set appropriate scrape interval

Testing