diff --git a/examples/basic-metrics/main.go b/examples/basic-metrics/main.go new file mode 100644 index 0000000..2ca517e --- /dev/null +++ b/examples/basic-metrics/main.go @@ -0,0 +1,46 @@ +// Prometheus metrics: counter, histogram, gauge, and /metrics endpoint. +package main + +import ( + "fmt" + "log" + "math/rand/v2" + "net/http" + "time" + + "git.codelab.vc/pkg/obsx" +) + +func main() { + metrics := obsx.NewMetrics(obsx.MetricsConfig{ + Namespace: "myapp", + Subsystem: "api", + }) + + requests := metrics.Counter("requests_total", "Total HTTP requests", "method", "status") + duration := metrics.Histogram("request_duration_seconds", "Request latency", nil, "method") + inflight := metrics.Gauge("inflight_requests", "Current in-flight requests") + + mux := http.NewServeMux() + + mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) { + inflight.WithLabelValues().Inc() + defer inflight.WithLabelValues().Dec() + + start := time.Now() + + // Simulate work. + time.Sleep(time.Duration(rand.IntN(100)) * time.Millisecond) + + w.WriteHeader(http.StatusOK) + fmt.Fprintln(w, "hello, world") + + requests.WithLabelValues("GET", "200").Inc() + duration.WithLabelValues("GET").Observe(time.Since(start).Seconds()) + }) + + mux.Handle("GET /metrics", metrics.Handler()) + + log.Println("listening on :8080 (try GET /hello, GET /metrics)") + log.Fatal(http.ListenAndServe(":8080", mux)) +}