// Command service is a minimal microservice instrumented with obsx. // // go run ./examples/service // curl localhost:8080/hello/world // curl localhost:9090/metrics // curl localhost:9090/readyz // // Set OBSX_TRACING_ENDPOINT=localhost:4317 to export traces to a collector. package main import ( "context" "errors" "log/slog" "math/rand/v2" "net/http" "os" "os/signal" "syscall" "time" "git.codelab.vc/pkg/obsx" ) func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() o, err := obsx.New(ctx, obsx.Config{ ServiceName: "greeter", ServiceVersion: "0.1.0", Environment: "dev", Admin: obsx.AdminConfig{Addr: ":9090"}, }.WithEnv()) if err != nil { slog.Error("observability setup failed", "error", err) os.Exit(1) } defer func() { if err := o.Shutdown(context.Background()); err != nil { slog.Error("observability shutdown failed", "error", err) } }() // Business metric under the service namespace. greetings := o.Metrics().Counter("greetings_total", "Greetings sent.", "lang") o.Health().AddReadinessCheck("storage", func(ctx context.Context) error { return nil // e.g. db.PingContext(ctx) }) mux := http.NewServeMux() mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) { err := o.Track(r.Context(), "storage.load_template", func(ctx context.Context) error { time.Sleep(time.Duration(rand.IntN(20)) * time.Millisecond) if rand.IntN(10) == 0 { return errors.New("template cache miss") } return nil }) if err != nil { slog.WarnContext(r.Context(), "falling back to default template", "error", err) } greetings.WithLabelValues("en").Inc() _, _ = w.Write([]byte("hello, " + r.PathValue("name") + "\n")) }) srv := &http.Server{ Addr: ":8080", Handler: o.HTTPMiddleware(mux), ReadHeaderTimeout: 5 * time.Second, } go func() { slog.Info("http server started", "addr", srv.Addr) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { slog.Error("http server failed", "error", err) stop() } }() <-ctx.Done() slog.Info("shutting down") o.Health().SetReady(false) shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { slog.Error("http server shutdown failed", "error", err) } }