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
@@ -0,0 +1,332 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
)
|
||||
|
||||
// newTestObserver creates an Observer exporting spans to memory and logging
|
||||
// to a buffer. Global state touched by New is restored on cleanup.
|
||||
func newTestObserver(t *testing.T, cfg Config) (*Observer, *tracetest.InMemoryExporter, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
prevTP, prevProp, prevLog := otel.GetTracerProvider(), otel.GetTextMapPropagator(), slog.Default()
|
||||
t.Cleanup(func() {
|
||||
otel.SetTracerProvider(prevTP)
|
||||
otel.SetTextMapPropagator(prevProp)
|
||||
slog.SetDefault(prevLog)
|
||||
})
|
||||
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
var logs bytes.Buffer
|
||||
if cfg.ServiceName == "" {
|
||||
cfg.ServiceName = "orders"
|
||||
}
|
||||
cfg.Tracing.Exporter = exp
|
||||
cfg.Logging.Output = &logs
|
||||
|
||||
o, err := New(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = o.Shutdown(context.Background()) })
|
||||
return o, exp, &logs
|
||||
}
|
||||
|
||||
// flushSpans exports spans buffered by the batch span processor.
|
||||
func flushSpans(t *testing.T, o *Observer, exp *tracetest.InMemoryExporter) tracetest.SpanStubs {
|
||||
t.Helper()
|
||||
if err := o.TracerProvider().(*sdktrace.TracerProvider).ForceFlush(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return exp.GetSpans()
|
||||
}
|
||||
|
||||
func TestNew_Defaults(t *testing.T) {
|
||||
o, _, logs := newTestObserver(t, Config{ServiceVersion: "1.2.3", Environment: "test"})
|
||||
|
||||
o.Logger().Info("ready")
|
||||
var rec map[string]any
|
||||
if err := json.Unmarshal(logs.Bytes(), &rec); err != nil {
|
||||
t.Fatalf("invalid log %q: %v", logs.String(), err)
|
||||
}
|
||||
if rec["service"] != "orders" || rec["version"] != "1.2.3" || rec["env"] != "test" {
|
||||
t.Errorf("service attributes missing from log: %v", rec)
|
||||
}
|
||||
|
||||
if otel.GetTracerProvider() != o.TracerProvider() {
|
||||
t.Error("tracer provider not installed globally")
|
||||
}
|
||||
|
||||
body := scrape(t, o.Metrics())
|
||||
if !strings.Contains(body, `service_build_info{`) || !strings.Contains(body, `service="orders"`) || !strings.Contains(body, `version="1.2.3"`) {
|
||||
t.Errorf("service_build_info missing:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, "go_goroutines") {
|
||||
t.Error("Go runtime metrics missing")
|
||||
}
|
||||
|
||||
if o.AdminAddr() != "" {
|
||||
t.Error("admin server must not start without Admin.Addr")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew_InvalidConfig(t *testing.T) {
|
||||
if _, err := New(context.Background(), Config{Logging: LogConfig{Level: "loud"}}); err == nil {
|
||||
t.Error("expected error for invalid log level")
|
||||
}
|
||||
if _, err := New(context.Background(), Config{Tracing: TracerConfig{Endpoint: "localhost:4317", Protocol: "zipkin"}}); err == nil {
|
||||
t.Error("expected error for unsupported protocol")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_EndToEndHTTP(t *testing.T) {
|
||||
o, exp, logs := newTestObserver(t, Config{})
|
||||
|
||||
// Downstream service called through the instrumented client.
|
||||
downstream := httptest.NewServer(o.HTTPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
o.Logger().InfoContext(r.Context(), "downstream handled")
|
||||
})))
|
||||
defer downstream.Close()
|
||||
|
||||
client := o.HTTPClient()
|
||||
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 nil })
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
req, _ := http.NewRequestWithContext(r.Context(), "GET", downstream.URL, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
resp.Body.Close()
|
||||
})
|
||||
srv := httptest.NewServer(o.HTTPMiddleware(mux))
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := http.Get(srv.URL + "/orders/42")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
// All spans belong to one trace: server -> track + client -> downstream server.
|
||||
spans := flushSpans(t, o, exp)
|
||||
if len(spans) != 4 {
|
||||
t.Fatalf("got %d spans, want 4", len(spans))
|
||||
}
|
||||
traceID := spans[0].SpanContext.TraceID()
|
||||
for _, s := range spans {
|
||||
if s.SpanContext.TraceID() != traceID {
|
||||
t.Errorf("span %q is in a different trace", s.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Downstream log line carries the shared trace ID.
|
||||
if !strings.Contains(logs.String(), `"msg":"downstream handled"`) || !strings.Contains(logs.String(), traceID.String()) {
|
||||
t.Errorf("log correlation broken:\n%s", logs.String())
|
||||
}
|
||||
|
||||
body := scrape(t, o.Metrics())
|
||||
for _, want := range []string{
|
||||
`http_server_requests_total{code="200",method="GET",route="/orders/{id}"} 1`,
|
||||
`http_client_requests_total{code="200",`,
|
||||
`operation_duration_seconds_count{operation="db.get_order",status="ok"} 1`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_TrackError(t *testing.T) {
|
||||
o, exp, _ := newTestObserver(t, Config{})
|
||||
|
||||
want := errors.New("not found")
|
||||
err := o.Track(context.Background(), "db.query", func(ctx context.Context) error { return want })
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("Track returned %v", err)
|
||||
}
|
||||
|
||||
spans := flushSpans(t, o, exp)
|
||||
if len(spans) != 1 || spans[0].Name != "db.query" || spans[0].Status.Code != codes.Error {
|
||||
t.Errorf("unexpected spans: %+v", spans)
|
||||
}
|
||||
if !strings.Contains(scrape(t, o.Metrics()), `operation_duration_seconds_count{operation="db.query",status="error"} 1`) {
|
||||
t.Error("error status not recorded")
|
||||
}
|
||||
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
_ = o.Track(context.Background(), "job", func(ctx context.Context) error { panic("boom") })
|
||||
}()
|
||||
if !strings.Contains(scrape(t, o.Metrics()), `operation_duration_seconds_count{operation="job",status="error"} 1`) {
|
||||
t.Error("panic not recorded as error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_AdminServer(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{Addr: "127.0.0.1:0"}})
|
||||
base := "http://" + o.AdminAddr()
|
||||
|
||||
get := func(path string) (int, string) {
|
||||
t.Helper()
|
||||
resp, err := http.Get(base + path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b)
|
||||
}
|
||||
|
||||
for path, want := range map[string]string{
|
||||
"/metrics": "service_build_info",
|
||||
"/healthz": `"status": "ok"`,
|
||||
"/livez": `"status": "ok"`,
|
||||
"/readyz": `"status": "ok"`,
|
||||
"/buildinfo": `"service": "orders"`,
|
||||
"/loglevel": `"level": "INFO"`,
|
||||
"/debug/pprof/": "goroutine",
|
||||
} {
|
||||
code, body := get(path)
|
||||
if code != http.StatusOK || !strings.Contains(body, want) {
|
||||
t.Errorf("GET %s = %d, want 200 containing %q:\n%s", path, code, want, body)
|
||||
}
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest("PUT", base+"/loglevel?level=debug", nil)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || !o.Logger().Enabled(context.Background(), -4) {
|
||||
t.Errorf("log level not changed: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
req, _ = http.NewRequest("PUT", base+"/loglevel", strings.NewReader("nonsense"))
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("invalid level code = %d, want 400", resp.StatusCode)
|
||||
}
|
||||
|
||||
o.Health().AddReadinessCheck("db", func(ctx context.Context) error { return errors.New("down") })
|
||||
if code, _ := get("/readyz"); code != http.StatusServiceUnavailable {
|
||||
t.Errorf("/readyz = %d, want 503", code)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := o.Shutdown(ctx); err != nil {
|
||||
t.Fatalf("Shutdown: %v", err)
|
||||
}
|
||||
if _, err := http.Get(base + "/healthz"); err == nil {
|
||||
t.Error("admin server still serving after Shutdown")
|
||||
}
|
||||
if err := o.Shutdown(ctx); err != nil {
|
||||
t.Errorf("second Shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_AdminDisablePprof(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{DisablePprof: true}})
|
||||
w := httptest.NewRecorder()
|
||||
o.AdminHandler().ServeHTTP(w, httptest.NewRequest("GET", "/debug/pprof/", nil))
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("pprof code = %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_AdminAddrInUse(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{Addr: "127.0.0.1:0"}})
|
||||
_, err := New(context.Background(), Config{
|
||||
Admin: AdminConfig{Addr: o.AdminAddr()},
|
||||
Logging: LogConfig{Output: io.Discard},
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("expected listen error for busy address")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_ShutdownMarksNotReady(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{})
|
||||
if err := o.Shutdown(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o.Health().CheckReadiness(context.Background()).Healthy() {
|
||||
t.Error("service must not be ready after Shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_AccessLogDisabled(t *testing.T) {
|
||||
o, _, logs := newTestObserver(t, Config{DisableAccessLog: true})
|
||||
o.HTTPMiddleware(http.NotFoundHandler()).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
|
||||
if strings.Contains(logs.String(), "http request") {
|
||||
t.Errorf("access log written although disabled: %s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_WithEnv(t *testing.T) {
|
||||
t.Setenv("OTEL_SERVICE_NAME", "from-otel")
|
||||
t.Setenv("OBSX_SERVICE_NAME", "from-obsx")
|
||||
t.Setenv("OBSX_ENVIRONMENT", "staging")
|
||||
t.Setenv("OBSX_LOG_LEVEL", "debug")
|
||||
t.Setenv("OBSX_TRACING_SAMPLER", "0.25")
|
||||
t.Setenv("OBSX_TRACING_DISABLED", "true")
|
||||
t.Setenv("OBSX_HEALTH_TIMEOUT", "3s")
|
||||
t.Setenv("OBSX_ADMIN_ADDR", ":9999")
|
||||
t.Setenv("OBSX_DISABLE_ACCESS_LOG", "not-a-bool")
|
||||
|
||||
cfg := Config{ServiceName: "from-code", Logging: LogConfig{Format: "text"}}.WithEnv()
|
||||
|
||||
if cfg.ServiceName != "from-obsx" {
|
||||
t.Errorf("ServiceName = %q", cfg.ServiceName)
|
||||
}
|
||||
if cfg.Environment != "staging" || cfg.Logging.Level != "debug" || cfg.Logging.Format != "text" {
|
||||
t.Errorf("unexpected config: %+v", cfg)
|
||||
}
|
||||
if cfg.Tracing.Sampler != 0.25 || !cfg.Tracing.Disabled {
|
||||
t.Errorf("unexpected tracing config: %+v", cfg.Tracing)
|
||||
}
|
||||
if cfg.Health.Timeout != 3*time.Second || cfg.Admin.Addr != ":9999" {
|
||||
t.Errorf("unexpected health/admin config: %+v %+v", cfg.Health, cfg.Admin)
|
||||
}
|
||||
if cfg.DisableAccessLog {
|
||||
t.Error("malformed bool must be ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_DefaultsInheritIdentity(t *testing.T) {
|
||||
cfg := Config{ServiceName: "svc", ServiceVersion: "v1", Environment: "prod"}
|
||||
cfg.defaults()
|
||||
if cfg.Tracing.ServiceName != "svc" || cfg.Tracing.ServiceVersion != "v1" || cfg.Tracing.Environment != "prod" {
|
||||
t.Errorf("tracing identity not inherited: %+v", cfg.Tracing)
|
||||
}
|
||||
|
||||
cfg = Config{}
|
||||
cfg.defaults()
|
||||
if cfg.ServiceName == "" {
|
||||
t.Error("ServiceName must default to the executable name")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user