Files
obsx/example_test.go
T
Aleksey ShakhmatovandClaude 2c83b28342
CI / test (push) Successful in 1m17s
Publish / publish (push) Successful in 1m24s
Release v1.0.0: HTTP instrumentation, slog correlation, TLS by default
Add HTTPMiddleware, HTTPTransport and LogHandler; extend TracerConfig with
Insecure, Headers and Attributes; install W3C propagators; parent-based
sampling; end-to-end OTLP export tests; update dependencies (Go 1.26).

Breaking since v0.2.0: the OTLP connection uses TLS unless Insecure is set.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-10 20:20:09 +03:00

46 lines
1.2 KiB
Go

package obsx_test
import (
"context"
"log"
"log/slog"
"net/http"
"os"
"git.codelab.vc/pkg/obsx"
)
// A service with traces, metrics and trace-correlated logs.
func Example() {
ctx := context.Background()
shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{
ServiceName: "orders-api",
Endpoint: "localhost:4317",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer shutdown(ctx)
slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil))))
metrics := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "orders"})
orders := metrics.Counter("created_total", "Orders created.", "kind")
mux := http.NewServeMux()
mux.Handle("GET /metrics", metrics.Handler())
mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
ctx, span := obsx.StartSpan(r.Context(), "create-order")
defer span.End()
orders.WithLabelValues("web").Inc()
slog.InfoContext(ctx, "order created") // carries trace_id and span_id
})
// Outgoing calls made with this client continue the current trace.
_ = &http.Client{Transport: obsx.HTTPTransport(nil)}
_ = http.ListenAndServe(":8080", obsx.HTTPMiddleware(metrics)(mux))
}