Files
obsx/example_test.go
T
M.ShakhmatovandClaude Fable 5.2 8837e8d316
CI / test (push) Successful in 1m12s
Deprecate v1.0.0 HTTP and log helpers in favour of the toolkit API
LogHandler and HTTPTransport now delegate to NewTraceHandler and
NewHTTPTransport. HTTPMiddleware keeps its v1.0.0 metric names but
shares responseWriter and normalizeMethod with NewHTTPMiddleware.
The package example shows obsx.New.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:43:33 +03:00

143 lines
4.3 KiB
Go

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 Example() {
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", Insecure: true, 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
}