Go developers often seek robust observability to monitor API performance, track request volumes, and understand system behavior in production environments. Prometheus stands out as an excellent solution for these needs. However, integrating Prometheus metrics into Go applications can frequently lead to verbose, boilerplate code, cluttering your codebase with repetitive setup.

This is where prometric-go steps in – a minimalist yet powerful Go library designed to significantly reduce the overhead of exposing Prometheus metrics. By wrapping Prometheus’s client_golang, prometric-go offers an idiomatic and streamlined approach to application monitoring, allowing developers to focus on core business logic rather than metric configuration.

What is Prometric-Go?

prometric-go is a lightweight Go library that provides ready-to-use metrics and helper functions, making observability plug-and-play for your HTTP servers and microservices. It’s built to simplify common monitoring tasks, offering:

  • 🌐 Comprehensive HTTP Request Tracking: Automatically monitors latency, request and response sizes, and in-flight requests.
  • ⚙️ Efficient CRUD Operation Metrics: Tracks total operations, durations, and object counts for database interactions.
  • ❤️ Essential Application Health Metrics: Provides insights into CPU and memory usage.
  • 🧱 Flexible Custom Metric Helpers: Simplifies the creation and registration of your own tailored metrics.

Say Goodbye to Boilerplate: Getting Started with Ease

Integrating prometric-go is straightforward.

Installation:

go get github.com/peek8/prometric-go/prometrics

Import:

import "github.com/peek8/prometric-go/prometrics"

To begin, simply expose a /metrics endpoint on your HTTP server:

package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
    mux := http.NewServeMux()
    mux.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":7080", mux)
}

With just a few lines, you now have a fully operational Prometheus endpoint at `http://localhost:7080/metrics`.

Automated HTTP Request Monitoring

prometric-go excels at automatically tracking key HTTP request metrics by wrapping your handlers with its Prometheus middleware:

handler := prometrics.InstrumentHttpHandler("/person", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, Prometheus!"))
}))
http.Handle("/", handler)
http.ListenAndServe(":7080", nil)

This middleware automatically records http_requests_total, http_request_duration_seconds, http_requests_in_flight, http_request_size_bytes, and http_response_size_bytes, providing granular insights into your application’s performance.

Streamlined CRUD Operation Tracking

Beyond HTTP, the library also offers dedicated metrics for monitoring your database CRUD operations:

// Example: create user in DB here
tracker := prometrics.TrackCRUD("user", "create")
defer tracker(time.Now())

This snippet effortlessly records crud_operations_total, object_operation_duration_seconds, and object_count, giving you a clear picture of your data layer’s activity. You can also manually control object counts:

prometrics.SetObjectCount("user", 100)
prometrics.IncObjectCount("user")
prometrics.DecObjectCount("user")

Essential System Health Metrics

For a complete observability picture, prometric-go can collect lightweight system metrics (CPU and memory usage) in a background goroutine or via middleware:

// Collect health metrics in 10s interval
ctx, cancel := context.WithCancel(context.Background(), 10)
go prometrics.CollectSystemMetricsLoop(ctx)

// Or using middleware for http endpoints
mux := http.NewServeMux()
mux.Handle("/metrics", prometrics.HealthMiddleware(promhttp.Handler()))

Seamless Gin Framework Integration

For those utilizing the Gin Web framework, prometric-go provides dedicated middlewares:

r := gin.Default()
r.Use(prometrics.GinMiddleware()) // For http metrics
r.Use(prometrics.GinHealthMiddleware()) // For health metrics

r.GET("/ping", func(c *gin.Context) {
  c.JSON(200, gin.H{"msg": "pong"})
})

r.GET("/person", func(c *gin.Context) {
  defer prometrics.TrackCRUD("person", "Get")(time.Now())
  c.JSON(200, gin.H{"name": "asraf"})
})

Visualizing Your Data with Grafana

Once your application exposes the /metrics endpoint, you can easily scrape it with Prometheus:

scrape_configs:
  - job_name: 'prometric-go-demo'
    static_configs:
      - targets: ['localhost:7080']

Then, create insightful dashboards in Grafana with panels displaying request duration heatmaps, total requests per endpoint, and in-flight request gauges.

The Philosophy Behind Prometric-Go

The library was born out of a desire to eliminate repetitive Prometheus setup in Go microservices. Key design goals included:

  • Quick Start: Provide immediately useful metrics without complex configuration.
  • Self-Registration: Automatically register all metrics using promauto.
  • Safe Concurrency: Ensure all metric operations are goroutine-safe.
  • GoDoc First: Maintain clear and comprehensive documentation for all exported symbols.
  • Composable Structure: Organize code into logical submodules for maintainability.

prometric-go isn’t intended to replace Prometheus but rather to enhance its usability for everyday Go developers, making observability an inherent part of the development workflow.

Roadmap for Future Enhancements

The project has an exciting future, with plans for:

  • More metrics and customization options.
  • Integration with OpenTelemetry.
  • Customizable metric namespaces/prefixes.
  • Built-in middlewares for other popular Go frameworks (e.g., Chi).
  • Out-of-the-box Grafana dashboards.

Conclusion

prometric-go empowers Go developers to achieve simple, standardized, and developer-friendly Prometheus metrics. Whether you’re building an HTTP API, a CLI tool, or a microservice, it allows you to concentrate on delivering business value, freeing you from the burdens of boilerplate metrics wiring.

Give it a try!

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed