Documentation
¶
Overview ¶
Package obs gives Go HTTP services the same Prometheus metrics everywhere: RED metrics (rate, errors, duration) of incoming requests labeled by route template, RED metrics of outgoing requests labeled by host, and the Go runtime and process collectors, all in a private registry.
Identical metric names across services are the point: one dashboard and one set of alert rules then work for every service, switched by a label the scraper adds.
Incoming requests ¶
Obs.Middleware wraps any http.Handler. The route label comes from a RouteFunc, which must return the route template ("/v1/users/{id}"), never the raw path:
- MuxRoute and Mux.RouteFunc read it from a standard http.ServeMux (Go 1.22 patterns);
- the muxobs package reads it from gorilla/mux;
- the fiberobs package provides a middleware for Fiber v2;
- for chi, a one-line RouteFunc returns chi.RouteContext(r.Context()).RoutePattern().
Requests that match no route are labeled "other" (RouteOther). A 5xx written after the client went away is counted as 499 (StatusClientClosedRequest), so abandoned requests do not look like server failures.
Outgoing requests ¶
Obs.Transport wraps an http.RoundTripper and labels requests by host; requests that got no response at all are counted with status="error".
Exposition ¶
Obs.Handler serves the registry on any router; Obs.Serve runs a separate management server for /metrics and anything added with Obs.Mount. The registry is private rather than prometheus.DefaultRegisterer, so the exposition holds exactly what the service registers, and Obs.Registry accepts the service's own metrics.
Route tables and OpenAPI ¶
The same route tables that label metrics can be served as a minimal OpenAPI 3.1 document (paths and methods only): Mux.MountOpenAPI for net/http, and MountOpenAPI in muxobs and fiberobs.
Example ¶
The quick start from the README: RED metrics per route template for a standard http.ServeMux, exposed on /metrics.
package main
import (
"fmt"
"log"
"net/http"
obs "github.com/ly-solutions/go-obs"
)
func main() {
o := obs.New()
mux := obs.NewMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "user %s\n", r.PathValue("id"))
})
mux.Handle("GET /metrics", o.Handler())
log.Fatal(http.ListenAndServe(":8080", o.Middleware(mux.RouteFunc())(mux)))
}
Output:
Index ¶
- Constants
- Variables
- func IsInternalPath(path string) bool
- func OpenAPI(title, version string, routes []Route) map[string]any
- func OpenAPIHandler(title, version string, routes RoutesFunc) http.Handler
- type Mux
- func (m *Mux) Handle(pattern string, handler http.Handler, methods ...string)
- func (m *Mux) HandleFunc(pattern string, handler http.HandlerFunc, methods ...string)
- func (m *Mux) MountOpenAPI(title, version string)
- func (m *Mux) RouteFunc() RouteFunc
- func (m *Mux) Routes() []Route
- func (m *Mux) Undocumented() []string
- type Obs
- func (o *Obs) Handler() http.Handler
- func (o *Obs) InFlight() prometheus.Gauge
- func (o *Obs) Middleware(route RouteFunc) func(http.Handler) http.Handler
- func (o *Obs) Mount(path string, handler http.Handler)
- func (o *Obs) ObserveRequest(method, route string, status int, elapsed time.Duration)
- func (o *Obs) Registry() *prometheus.Registry
- func (o *Obs) RequestsCounter(method, route, status string) (prometheus.Counter, error)
- func (o *Obs) Serve(ctx context.Context, addr string) error
- func (o *Obs) Transport(base http.RoundTripper) http.RoundTripper
- type Route
- type RouteFunc
- type RoutesFunc
Examples ¶
Constants ¶
const RouteOther = "other"
RouteOther is the route label of a request that matched no known route.
const StatusClientClosedRequest = 499
StatusClientClosedRequest is the status a request is counted under when the client went away before the response. It is not a standard HTTP status; 499 is the nginx convention, so the service's metrics agree with nginx-style access logs.
Variables ¶
var DefaultBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}
DefaultBuckets are the latency buckets of both request duration histograms, in seconds. They reach higher than prometheus.DefBuckets so that slow endpoints show up as a tail between 2.5 s and 10 s instead of disappearing into +Inf.
Functions ¶
func IsInternalPath ¶
IsInternalPath reports whether path is an operational endpoint that every service has (metrics, health probes, the OpenAPI document itself) and that says nothing about the service's API. Such paths are left out of route tables and OpenAPI documents by every router integration in this module.
The list is /metrics, /healthz, /health, /health/live, /health/ready, /readyz, /livez and /openapi.json.
func OpenAPI ¶
OpenAPI builds an OpenAPI 3.1 document from a route table, as a value ready for encoding/json.
The document lists paths and methods only; every operation has a single "default" response. Request and response schemas are not there, because a router does not know them. What it does answer precisely, and without annotations that drift from the code, is the first question about any service: which endpoints it has. The table comes from the router itself, the same source the metrics are labeled from.
Routes with a method OpenAPI does not define, an empty path or the RouteOther path are skipped. Paths are written as given; OpenAPI expects "{name}" parameters, which is the syntax of http.ServeMux, chi and gorilla/mux.
func OpenAPIHandler ¶
func OpenAPIHandler(title, version string, routes RoutesFunc) http.Handler
OpenAPIHandler serves the OpenAPI document of a route table as JSON, with Cache-Control: no-store.
routes is called on every request rather than once at startup: some routes are registered while the service initializes, and a snapshot taken too early would be incomplete without any error. A nil routes serves a document without paths.
Types ¶
type Mux ¶
Mux is a standard http.ServeMux that remembers what was registered on it.
Fiber and gorilla/mux can list their routes, so an OpenAPI document built from them cannot drift from the code. A plain http.ServeMux cannot be asked for its routes at all; the only moment that table exists is registration, and Mux records it there. The pattern string is the very one used for routing, so there is no second copy to get wrong.
Mux does not guess methods. A pattern without a method ("/v1/feed") accepts any request, and only the handler knows which methods it really serves. Writing "get" into the document because that is the common case would present a guess as a contract. Such routes stay out of the document and are listed by Undocumented instead.
Host patterns ("example.com/path") are recorded as paths as they are.
Example ¶
Mux records its routes as they are registered. Routes without a method stay out of the table and are listed by Undocumented.
package main
import (
"fmt"
"net/http"
obs "github.com/ly-solutions/go-obs"
)
func main() {
mux := obs.NewMux()
noop := func(http.ResponseWriter, *http.Request) {}
mux.HandleFunc("GET /v1/orders/{id}", noop)
mux.HandleFunc("/v1/search", noop, http.MethodGet, http.MethodPost)
mux.HandleFunc("/v1/legacy", noop)
mux.HandleFunc("GET /healthz", noop) // operational paths are skipped
for _, r := range mux.Routes() {
fmt.Println(r.Method, r.Path)
}
fmt.Println("undocumented:", mux.Undocumented())
}
Output: GET /v1/orders/{id} GET /v1/search POST /v1/search undocumented: [/v1/legacy]
func (*Mux) Handle ¶
Handle registers a handler and records it in the route table.
Methods come from a Go 1.22 pattern ("GET /v1/feed") or, for patterns that deliberately accept several methods and dispatch on them inside the handler, from the methods arguments. A method in the pattern wins over the arguments.
func (*Mux) HandleFunc ¶
func (m *Mux) HandleFunc(pattern string, handler http.HandlerFunc, methods ...string)
HandleFunc is Handle for a handler function.
func (*Mux) MountOpenAPI ¶
MountOpenAPI serves the OpenAPI document of the route table at "GET /openapi.json".
The table is read on every request, not now: routes registered after this call are included, so the order of calls does not matter.
Example ¶
The OpenAPI document lists the routes the router knows, with no annotations.
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
obs "github.com/ly-solutions/go-obs"
)
func main() {
mux := obs.NewMux()
mux.HandleFunc("GET /v1/orders/{id}", func(http.ResponseWriter, *http.Request) {})
mux.MountOpenAPI("orders", "1.0.0")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/openapi.json", nil))
var doc struct {
OpenAPI string `json:"openapi"`
Paths map[string]map[string]any `json:"paths"`
}
if err := json.NewDecoder(rec.Body).Decode(&doc); err != nil {
fmt.Println(err)
return
}
for path, ops := range doc.Paths {
for method := range ops {
fmt.Println(doc.OpenAPI, method, path)
}
}
}
Output: 3.1.0 get /v1/orders/{id}
func (*Mux) RouteFunc ¶
RouteFunc returns the route template for metrics. It is MuxRoute for the embedded http.ServeMux.
func (*Mux) Undocumented ¶
Undocumented lists, sorted, the paths registered without a method, which therefore stay out of the OpenAPI document.
It exists so that an endpoint does not drop out of the document silently: a service can assert in a test that this list is empty.
type Obs ¶
type Obs struct {
// contains filtered or unexported fields
}
Obs owns a private Prometheus registry and the HTTP metrics registered in it. Create one per process with New and share it between the server middleware, the client transport and the metrics endpoint. All methods are safe for concurrent use.
func New ¶
func New() *Obs
New creates a registry with the Go runtime and process collectors and the HTTP server and client metrics.
New adds no service, job or instance labels on purpose: the scraper attaches them (for example from Kubernetes pod labels). If the application set them itself, the go_* and process_* series would lack them and dashboards could not tell one service's runtime from another's.
func (*Obs) Handler ¶
Handler returns the Prometheus exposition of the registry, ready to be mounted on any router.
A collector that fails while being gathered does not take the endpoint down: the response is still a 200 with every metric that could be collected, and the failure is counted in promhttp_metric_handler_errors_total{cause="gathering"} in the same registry. With promhttp's default, a single bad collector would turn the whole response into a 500, hiding the runtime and HTTP metrics while the target still looks healthy to the scraper.
func (*Obs) InFlight ¶
func (o *Obs) InFlight() prometheus.Gauge
InFlight returns the gauge of requests being served, for middleware of other routers.
func (*Obs) Middleware ¶
Middleware records RED metrics (rate, errors, duration) of incoming requests, labeled with the route template that route returns. A nil route labels every request as RouteOther.
A request the client abandoned is not a server failure. When the client closes the connection, the request context is canceled, calls to upstream services return context.Canceled, and the handler typically writes a 502 or 500 into a connection nobody reads anymore. Counted as is, a user double-clicking a button would page whoever alerts on 5xx. So a 5xx written after the request context was canceled is counted as 499 (StatusClientClosedRequest). Only the label changes; the handler's response is left alone. An expired deadline (context.DeadlineExceeded) is not affected: that is the server's own timeout, and the client was still waiting.
Example ¶
Requests to /users/1 and /users/2 share one series, labeled with the route template. Requests that match no route are labeled "other".
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/prometheus/client_golang/prometheus/testutil"
obs "github.com/ly-solutions/go-obs"
)
func main() {
o := obs.New()
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler := o.Middleware(obs.MuxRoute(mux))(mux)
for _, path := range []string{"/users/1", "/users/2", "/nope"} {
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, path, nil))
}
users, _ := o.RequestsCounter("GET", "/users/{id}", "200")
other, _ := o.RequestsCounter("GET", obs.RouteOther, "404")
fmt.Println("GET /users/{id} 200:", testutil.ToFloat64(users))
fmt.Println("GET other 404:", testutil.ToFloat64(other))
}
Output: GET /users/{id} 200: 2 GET other 404: 1
func (*Obs) Mount ¶
Mount adds a handler for an exact path on the management server that Serve runs, next to /metrics.
It is meant for things that belong on an internal port rather than the public one, such as the OpenAPI document of a gateway: its route list is a map of everything behind it.
Mount may be called before or after Serve: the management server looks the path up on every request. Mounting the same path again replaces the handler; a nil handler is ignored.
func (*Obs) ObserveRequest ¶
ObserveRequest records one incoming request. It is meant for middleware of routers that do not use the http.Handler chain (see the fiberobs package). An empty route is recorded as RouteOther.
func (*Obs) Registry ¶
func (o *Obs) Registry() *prometheus.Registry
Registry returns the private registry, for example to register the service's own business metrics so that a single endpoint exposes everything.
Example ¶
Business metrics go into the same registry, so one endpoint exposes everything.
package main
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
obs "github.com/ly-solutions/go-obs"
)
func main() {
o := obs.New()
signups := prometheus.NewCounter(prometheus.CounterOpts{
Name: "signups_total",
Help: "Completed sign-ups.",
})
o.Registry().MustRegister(signups)
signups.Inc()
fmt.Println(testutil.ToFloat64(signups))
}
Output: 1
func (*Obs) RequestsCounter ¶
func (o *Obs) RequestsCounter(method, route, status string) (prometheus.Counter, error)
RequestsCounter returns the http_requests_total counter of one label set. It lets a service's tests check their own routes without parsing the text exposition.
func (*Obs) Serve ¶
Serve runs a separate management HTTP server on addr that exposes /metrics and the handlers added with Mount, and shuts it down gracefully when ctx is done.
A separate port keeps per-route latency, upstream health and runtime details off the public listener and out of the reach of the internet. Serve blocks; it returns nil after a shutdown caused by ctx, and the listen error otherwise (for example, when the port is taken).
Example ¶
Serve runs a management server for /metrics on its own port, away from the public listener, and stops it when the context is done. Mount adds more handlers to it, before or after Serve starts.
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
obs "github.com/ly-solutions/go-obs"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
o := obs.New()
public := obs.NewMux()
public.HandleFunc("GET /v1/orders/{id}", func(w http.ResponseWriter, _ *http.Request) {})
o.Mount("/openapi.json", obs.OpenAPIHandler("orders", "1.0.0", public.Routes))
go func() {
if err := o.Serve(ctx, ":9090"); err != nil {
log.Printf("management server: %v", err)
}
}()
srv := &http.Server{Addr: ":8080", Handler: o.Middleware(public.RouteFunc())(public)}
go func() { _ = srv.ListenAndServe() }()
<-ctx.Done()
_ = srv.Shutdown(context.Background())
}
Output:
func (*Obs) Transport ¶
func (o *Obs) Transport(base http.RoundTripper) http.RoundTripper
Transport wraps an http.RoundTripper and records RED metrics of outgoing requests. A nil base means http.DefaultTransport.
The label is the host (with port, if the URL has one), not the URL: an upstream API has many paths, and the question a dashboard answers is whether that neighbor is up and how fast it answers. A request that got no response at all (connection refused, timeout, canceled) is counted with status="error", so a broken link to an upstream is not mistaken for the absence of calls.
Example ¶
Outgoing requests are counted per upstream host.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
obs "github.com/ly-solutions/go-obs"
)
func main() {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
defer upstream.Close()
o := obs.New()
client := &http.Client{Transport: o.Transport(nil), Timeout: 2 * time.Second}
resp, err := client.Get(upstream.URL + "/ping")
if err != nil {
fmt.Println(err)
return
}
resp.Body.Close()
fmt.Println("series:", testutil.CollectAndCount(o.Registry(), "http_client_requests_total"))
}
Output: series: 1
type Route ¶
Route is one endpoint of a service: a method and a path template such as "/v1/users/{id}".
type RouteFunc ¶
RouteFunc returns the route template of a request: "/v1/users/{id}", not "/v1/users/17". A raw URL in a label explodes cardinality: every user would get a time series of their own, and so would every path a scanner tries.
The middleware calls it after the handler has returned, so routers that record the matched route on the request while routing (chi, gorilla/mux) can be read at that point.
func MuxRoute ¶
MuxRoute reads the route template from a standard http.ServeMux.
The middleware wraps the mux from the outside, while http.Request.Pattern is set inside the mux's ServeHTTP on a copy of the request and is not visible outside. So the pattern is looked up from the mux itself.
func StaticRoute ¶
StaticRoute labels every request with the same route. It suits services with a single endpoint, and tests.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fiberobs connects the metrics and route tables of the obs package to Fiber v2.
|
Package fiberobs connects the metrics and route tables of the obs package to Fiber v2. |
|
Package muxobs connects the metrics and route tables of the obs package to gorilla/mux.
|
Package muxobs connects the metrics and route tables of the obs package to gorilla/mux. |