fiberprometheus

repository·master·Indexed 42 days ago

https://github.com/ansrivas/fiberprometheus

A Prometheus middleware for the Fiber web framework in Go that automatically collects HTTP request metrics, including total counts, duration, and in-progress requests. Supports custom labels, namespaces, path normalization, and OpenTelemetry Exemplars for request latency histograms. Compatible with Go 1.22 or above and provides integration for Grafana visualization.

Tokens
1.7K
Snippets
5
Records
7
Agent score
3%

What's inside fiberprometheus

  1. Configure fiberprometheus middleware

    master

    The fiberprometheus middleware provides default Prometheus metrics for your Fiber application.

    Default Metrics

    • http_requests_total
    • http_request_duration_seconds
    • http_requests_in_progress_total

    Initialization Options

    You can initialize the middleware using several methods to define service identity and labels:

    1. Basic Service Name: fiberprometheus.New("service-name") sets the service name as a label.
    2. With Hierarchy: fiberprometheus.NewWith(servicename, namespace, subsystem) allows for structured labeling.
    3. With Custom Labels: fiberprometheus.NewWithLabels(labels, namespace, subsystem) where labels is a map[string]string.

    Middleware Configuration

    Once initialized, you can customize the behavior before applying it to the app:

    • RegisterAt(app, path): Registers the metrics endpoint (e.g., /metrics) on your Fiber application.
    • SetSkipPaths([]string{...}): Excludes specific paths from being recorded in metrics.
    • SetIgnoreStatusCodes([]int{...}): Excludes specific HTTP status codes from being recorded in metrics.

    After configuration, apply the middleware using app.Use(prometheus.Middleware).

    package main
    
    import (
      "github.com/ansrivas/fiberprometheus/v2"
      "github.com/gofiber/fiber/v2"
    )
    
    func main() {
      app := fiber.New()
    
      // Initialize with a service name
      prometheus := fiberprometheus.New("my-service-name")
      
      // Register the /metrics endpoint
      prometheus.RegisterAt(app, "/metrics")
      
      // Optional: Exclude specific paths
      prometheus.SetSkipPaths([]string{"/ping"})
      
      // Optional: Exclude specific status codes
      prometheus.SetIgnoreStatusCodes([]int{401, 403, 404})
      
      // Apply the middleware
      app.Use(prometheus.Middleware)
    
      app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello World")
      })
    
      app.Listen(":3000")
    }
  2. How FiberPrometheus metrics work

    master

    The FiberPrometheus middleware tracks three primary metrics for your Fiber application:

    1. requests_total (Counter): Counts total HTTP requests, partitioned by status_code, method, and path.
    2. request_duration_seconds (Histogram): Measures the latency of requests, partitioned by status_code, method, and path. It supports OpenTelemetry Exemplars; if a valid traceID is found in the request context, it is attached to the histogram observation.
    3. requests_in_progress_total (Gauge): Tracks the number of concurrent requests currently being processed, partitioned by method.

    Path Normalization: The middleware normalizes paths by removing trailing slashes to ensure consistent metric grouping (e.g., /users/ and /users are treated as the same path).

  3. Expose Prometheus metrics endpoint

    master

    To allow Prometheus to scrape your metrics, use the RegisterAt method. This registers a GET handler at the specified URL that serves the collected metrics using the promhttp handler. By default, it uses the internal gatherer from the FiberPrometheus instance.

    fp := fiberprometheus.New("my-service")
    app.Use(fp.Middleware)
    
    // Register the /metrics endpoint
    fp.RegisterAt(app, "/metrics")
  4. Initialize FiberPrometheus middleware

    master

    You can initialize the FiberPrometheus middleware using several constructor functions depending on your requirements for namespaces, subsystems, and custom labels.

    • New(serviceName string): Simplest way. Uses http namespace and empty subsystem. Adds service as a constant label.
    • NewWith(serviceName, namespace, subsystem string): Allows custom namespace and subsystem prefixes.
    • NewWithLabels(labels map[string]string, namespace, subsystem string): Allows custom constant labels for all metrics.
    • NewWithRegistry(registry prometheus.Registerer, serviceName, namespace, subsystem string, labels map[string]string): Uses a custom Prometheus registry.
    • NewWithDefaultRegistry(serviceName string): Uses the prometheus.DefaultRegisterer.
    // Example: Basic initialization
    fp := fiberprometheus.New("my-service")
    app.Use(fp.Middleware)
    
    // Example: Advanced initialization with custom labels and registry
    registry := prometheus.NewRegistry()
    fp := fiberprometheus.NewWithRegistry(
        registry, 
        "my-service", 
        "my_app", 
        "http", 
        map[string]string{"env": "production"},
    )
    app.Use(fp.Middleware)
  5. Configure paths and status codes to skip in metrics

    master

    You can prevent specific routes or HTTP status codes from being recorded in your Prometheus metrics using the following methods:

    • SetSkipPaths(paths []string): Provides a list of route paths that should be ignored by the middleware.
    • SetIgnoreStatusCodes(codes []int): Provides a list of HTTP status codes that should not be recorded.
    fp := fiberprometheus.New("my-service")
    
    // Skip metrics for health checks or specific routes
    fp.SetSkipPaths("/health", "/metrics")
    
    // Ignore 404s or other specific status codes
    fp.SetIgnoreStatusCodes("[]int{404}")
    
    app.Use(fp.Middleware)