Add Observer as a single entry point
obsx.New wires logger, tracer provider, metrics, health checks and the admin server (/metrics, /healthz, /readyz, /buildinfo, /loglevel, pprof). Adds Track for arbitrary operations, Config.WithEnv overrides, godoc examples and a runnable example service. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8398e81bc7
commit
be4330a9ee
7 files changed
+1087
-1
No files matched your search
+131
@@ -2,14 +2,145 @@ package obsx_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.codelab.vc/pkg/obsx"
|
||||
"google.golang.org/grpc"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
)
|
||||
|
||||
// A complete HTTP service: one call to New wires logging, tracing, metrics,
|
||||
// health checks and the admin server; instrumentation is a single wrapper.
|
||||
func ExampleNew() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
o, err := obsx.New(ctx, obsx.Config{
|
||||
ServiceName: "orders",
|
||||
ServiceVersion: "1.4.0",
|
||||
Environment: "production",
|
||||
Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Sampler: 0.1},
|
||||
Admin: obsx.AdminConfig{Addr: ":9090"},
|
||||
}.WithEnv())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer o.Shutdown(context.Background())
|
||||
|
||||
var db *sql.DB // your database
|
||||
o.Health().AddReadinessCheck("postgres", db.PingContext)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
err := o.Track(r.Context(), "db.get_order", func(ctx context.Context) error {
|
||||
return db.QueryRowContext(ctx, "SELECT 1").Err()
|
||||
})
|
||||
if err != nil {
|
||||
slog.ErrorContext(r.Context(), "get order failed", "error", err) // has trace_id
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
}
|
||||
})
|
||||
|
||||
srv := &http.Server{Addr: ":8080", Handler: o.HTTPMiddleware(mux)}
|
||||
go func() { _ = srv.ListenAndServe() }()
|
||||
|
||||
<-ctx.Done()
|
||||
o.Health().SetReady(false) // stop receiving traffic
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(shutdownCtx)
|
||||
}
|
||||
|
||||
// gRPC servers and clients are instrumented with ready-made options.
|
||||
func Example_grpc() {
|
||||
o, err := obsx.New(context.Background(), obsx.Config{ServiceName: "billing"})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer o.Shutdown(context.Background())
|
||||
|
||||
srv := grpc.NewServer(o.GRPCServerOptions()...)
|
||||
healthpb.RegisterHealthServer(srv, o.Health().GRPCServer())
|
||||
|
||||
conn, err := grpc.NewClient("payments:9000", o.GRPCDialOptions()...) // + transport credentials
|
||||
if err == nil {
|
||||
defer conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Outgoing HTTP calls propagate the trace and are measured per host.
|
||||
func ExampleObserver_HTTPClient() {
|
||||
o, _ := obsx.New(context.Background(), obsx.Config{ServiceName: "gateway"})
|
||||
defer o.Shutdown(context.Background())
|
||||
|
||||
client := o.HTTPClient()
|
||||
client.Timeout = 5 * time.Second
|
||||
|
||||
req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://users/api/v1/me", nil)
|
||||
if resp, err := client.Do(req); err == nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Business metrics share the service registry and are exposed on /metrics.
|
||||
func ExampleMetrics() {
|
||||
m := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "shop"})
|
||||
|
||||
orders := m.Counter("orders_created_total", "Orders created.", "payment_method")
|
||||
orders.WithLabelValues("card").Inc()
|
||||
|
||||
cart := m.Sub("cart").Histogram("items", "Items per cart.", []float64{1, 2, 5, 10, 20})
|
||||
cart.WithLabelValues().Observe(3)
|
||||
|
||||
queue := make(chan struct{}, 100)
|
||||
m.GaugeFunc("queue_depth", "Pending jobs.", func() float64 { return float64(len(queue)) })
|
||||
|
||||
http.Handle("/metrics", m.Handler())
|
||||
}
|
||||
|
||||
// Health checks run concurrently with a per-check timeout.
|
||||
func ExampleHealth() {
|
||||
h := obsx.NewHealth(obsx.HealthConfig{Timeout: 2 * time.Second})
|
||||
h.AddReadinessCheck("cache", func(ctx context.Context) error { return nil })
|
||||
|
||||
report := h.CheckReadiness(context.Background())
|
||||
fmt.Println(report.Status, report.Checks["cache"].Status)
|
||||
// Output: ok ok
|
||||
}
|
||||
|
||||
// Components can be used standalone without an Observer.
|
||||
func ExampleNewHTTPMiddleware() {
|
||||
m := obsx.NewMetrics(obsx.MetricsConfig{})
|
||||
logger, _ := obsx.NewLogger(obsx.LogConfig{Level: "info"})
|
||||
|
||||
mw := obsx.NewHTTPMiddleware(obsx.HTTPServerConfig{
|
||||
Metrics: m,
|
||||
Logger: logger,
|
||||
TraceIDHeader: "X-Trace-Id",
|
||||
})
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ping", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("pong")) })
|
||||
_ = http.ListenAndServe(":8080", mw(mux))
|
||||
}
|
||||
|
||||
// Trace wraps a unit of work in a span and records its error.
|
||||
func ExampleTrace() {
|
||||
err := obsx.Trace(context.Background(), "reconcile", func(ctx context.Context) error {
|
||||
slog.InfoContext(ctx, "reconciling", "trace_id", obsx.TraceID(ctx))
|
||||
return nil
|
||||
})
|
||||
_ = err
|
||||
}
|
||||
|
||||
// A service with traces, metrics and trace-correlated logs.
|
||||
func Example() {
|
||||
ctx := context.Background()
|
||||
|
||||
Reference in new issue
Block a user