261 lines
8.0 KiB
Go
261 lines
8.0 KiB
Go
// Package telemetry configures OpenTelemetry trace export, trace-correlated
|
|
// structured logging, HTTP span middleware, and an internal Prometheus /metrics
|
|
// endpoint using the Go standard library.
|
|
package telemetry
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/sdk/resource"
|
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
|
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
const (
|
|
otlpEndpointEnv = "OTEL_EXPORTER_OTLP_ENDPOINT"
|
|
metricsMediaType = "text/plain; version=0.0.4; charset=utf-8"
|
|
shutdownTimeout = 5 * time.Second
|
|
)
|
|
|
|
// Setup registers the W3C TraceContext propagator and, when
|
|
// OTEL_EXPORTER_OTLP_ENDPOINT is set, installs an OTLP/gRPC TracerProvider.
|
|
// The returned shutdown function flushes pending spans on exit.
|
|
func Setup(ctx context.Context, serviceName, version string) (func(context.Context) error, error) {
|
|
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
|
propagation.TraceContext{},
|
|
propagation.Baggage{},
|
|
))
|
|
if strings.TrimSpace(os.Getenv(otlpEndpointEnv)) == "" {
|
|
return func(context.Context) error { return nil }, nil
|
|
}
|
|
res, err := resource.Merge(resource.Default(), resource.NewWithAttributes(
|
|
semconv.SchemaURL,
|
|
semconv.ServiceName(serviceName),
|
|
semconv.ServiceVersion(version),
|
|
semconv.ServiceInstanceID(instanceID()),
|
|
))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("telemetry resource: %w", err)
|
|
}
|
|
exporter, err := otlptracegrpc.New(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("telemetry exporter: %w", err)
|
|
}
|
|
tp := sdktrace.NewTracerProvider(
|
|
sdktrace.WithBatcher(exporter),
|
|
sdktrace.WithResource(res),
|
|
)
|
|
otel.SetTracerProvider(tp)
|
|
return func(shutdownCtx context.Context) error {
|
|
if _, hasDeadline := shutdownCtx.Deadline(); !hasDeadline {
|
|
var cancel context.CancelFunc
|
|
shutdownCtx, cancel = context.WithTimeout(context.WithoutCancel(shutdownCtx), shutdownTimeout)
|
|
defer cancel()
|
|
}
|
|
return tp.Shutdown(shutdownCtx)
|
|
}, nil
|
|
}
|
|
|
|
func instanceID() string {
|
|
host, _ := os.Hostname()
|
|
return host + "-" + strconv.Itoa(os.Getpid())
|
|
}
|
|
|
|
// stampedKey marks a context whose log record already carries trace_id and
|
|
// span_id so nested trace handlers do not emit duplicate attributes.
|
|
type stampedKey struct{}
|
|
|
|
type logHandler struct {
|
|
inner slog.Handler
|
|
}
|
|
|
|
// NewLogHandler wraps base so log records emitted with an active span in ctx
|
|
// include trace_id and span_id attributes.
|
|
func NewLogHandler(base slog.Handler) slog.Handler {
|
|
return logHandler{inner: base}
|
|
}
|
|
|
|
func (h logHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
|
return h.inner.Enabled(ctx, level)
|
|
}
|
|
|
|
func (h logHandler) Handle(ctx context.Context, r slog.Record) error {
|
|
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() && ctx.Value(stampedKey{}) == nil {
|
|
r.AddAttrs(
|
|
slog.String("trace_id", sc.TraceID().String()),
|
|
slog.String("span_id", sc.SpanID().String()),
|
|
)
|
|
ctx = context.WithValue(ctx, stampedKey{}, true)
|
|
}
|
|
return h.inner.Handle(ctx, r)
|
|
}
|
|
|
|
func (h logHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
return logHandler{inner: h.inner.WithAttrs(attrs)}
|
|
}
|
|
|
|
func (h logHandler) WithGroup(name string) slog.Handler {
|
|
return logHandler{inner: h.inner.WithGroup(name)}
|
|
}
|
|
|
|
// Metrics tracks process-local HTTP request counts, latency sums, and Go
|
|
// runtime metrics for Prometheus scraping.
|
|
type Metrics struct {
|
|
started time.Time
|
|
inFlight atomic.Int64
|
|
requests2xx atomic.Int64
|
|
requests3xx atomic.Int64
|
|
requests4xx atomic.Int64
|
|
requests5xx atomic.Int64
|
|
requestsOther atomic.Int64
|
|
durationNanos atomic.Int64
|
|
durationCount atomic.Int64
|
|
}
|
|
|
|
// NewMetrics returns a Metrics collector anchored at the current time.
|
|
func NewMetrics() *Metrics {
|
|
return &Metrics{started: time.Now()}
|
|
}
|
|
|
|
// Middleware records HTTP request counts, durations, and in-flight requests,
|
|
// and wraps next in otelhttp.NewHandler for HTTP span creation.
|
|
func (m *Metrics) Middleware(next http.Handler) http.Handler {
|
|
instrumented := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
m.inFlight.Add(1)
|
|
start := time.Now()
|
|
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
|
defer func() {
|
|
m.inFlight.Add(-1)
|
|
m.recordRequest(sw.status, time.Since(start))
|
|
}()
|
|
next.ServeHTTP(sw, r)
|
|
})
|
|
return otelhttp.NewHandler(instrumented, "http",
|
|
otelhttp.WithFilter(func(r *http.Request) bool {
|
|
return !isProbeOrMetrics(r.URL.Path)
|
|
}),
|
|
)
|
|
}
|
|
|
|
func isProbeOrMetrics(path string) bool {
|
|
return strings.HasPrefix(path, "/health") || path == "/readyz" || path == "/startupz" || path == "/metrics"
|
|
}
|
|
|
|
func (m *Metrics) recordRequest(status int, took time.Duration) {
|
|
m.durationCount.Add(1)
|
|
m.durationNanos.Add(took.Nanoseconds())
|
|
switch status / 100 {
|
|
case 2:
|
|
m.requests2xx.Add(1)
|
|
case 3:
|
|
m.requests3xx.Add(1)
|
|
case 4:
|
|
m.requests4xx.Add(1)
|
|
case 5:
|
|
m.requests5xx.Add(1)
|
|
default:
|
|
m.requestsOther.Add(1)
|
|
}
|
|
}
|
|
|
|
type statusWriter struct {
|
|
http.ResponseWriter
|
|
status int
|
|
wroteHeader bool
|
|
}
|
|
|
|
func (w *statusWriter) WriteHeader(code int) {
|
|
if !w.wroteHeader {
|
|
w.status = code
|
|
w.wroteHeader = true
|
|
}
|
|
w.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (w *statusWriter) Write(p []byte) (int, error) {
|
|
if !w.wroteHeader {
|
|
w.wroteHeader = true
|
|
}
|
|
return w.ResponseWriter.Write(p)
|
|
}
|
|
|
|
func (w *statusWriter) Unwrap() http.ResponseWriter {
|
|
return w.ResponseWriter
|
|
}
|
|
|
|
// MetricsHandler serves Prometheus text format metrics on an internal endpoint.
|
|
func (m *Metrics) MetricsHandler() http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
var ms runtime.MemStats
|
|
runtime.ReadMemStats(&ms)
|
|
|
|
uptime := time.Since(m.started).Seconds()
|
|
durSec := float64(m.durationNanos.Load()) / float64(time.Second)
|
|
|
|
w.Header().Set("Content-Type", metricsMediaType)
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
_, _ = fmt.Fprintf(w,
|
|
"# HELP archie_uptime_seconds Process uptime in seconds.\n"+
|
|
"# TYPE archie_uptime_seconds gauge\n"+
|
|
"archie_uptime_seconds %.6f\n"+
|
|
"# HELP archie_http_requests_in_flight Current number of in-flight HTTP requests.\n"+
|
|
"# TYPE archie_http_requests_in_flight gauge\n"+
|
|
"archie_http_requests_in_flight %d\n"+
|
|
"# HELP archie_http_requests_total Total number of HTTP requests handled by status class.\n"+
|
|
"# TYPE archie_http_requests_total counter\n"+
|
|
"archie_http_requests_total{status=\"2xx\"} %d\n"+
|
|
"archie_http_requests_total{status=\"3xx\"} %d\n"+
|
|
"archie_http_requests_total{status=\"4xx\"} %d\n"+
|
|
"archie_http_requests_total{status=\"5xx\"} %d\n"+
|
|
"archie_http_requests_total{status=\"other\"} %d\n"+
|
|
"# HELP archie_http_request_duration_seconds Total HTTP request duration and count.\n"+
|
|
"# TYPE archie_http_request_duration_seconds summary\n"+
|
|
"archie_http_request_duration_seconds_sum %.6f\n"+
|
|
"archie_http_request_duration_seconds_count %d\n"+
|
|
"# HELP go_goroutines Number of goroutines that currently exist.\n"+
|
|
"# TYPE go_goroutines gauge\n"+
|
|
"go_goroutines %d\n"+
|
|
"# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use.\n"+
|
|
"# TYPE go_memstats_alloc_bytes gauge\n"+
|
|
"go_memstats_alloc_bytes %d\n"+
|
|
"# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use.\n"+
|
|
"# TYPE go_memstats_heap_inuse_bytes gauge\n"+
|
|
"go_memstats_heap_inuse_bytes %d\n"+
|
|
"# HELP go_memstats_sys_bytes Number of bytes obtained from system.\n"+
|
|
"# TYPE go_memstats_sys_bytes gauge\n"+
|
|
"go_memstats_sys_bytes %d\n"+
|
|
"# HELP go_gc_cycles_total Total number of completed GC cycles.\n"+
|
|
"# TYPE go_gc_cycles_total counter\n"+
|
|
"go_gc_cycles_total %d\n",
|
|
uptime,
|
|
m.inFlight.Load(),
|
|
m.requests2xx.Load(),
|
|
m.requests3xx.Load(),
|
|
m.requests4xx.Load(),
|
|
m.requests5xx.Load(),
|
|
m.requestsOther.Load(),
|
|
durSec,
|
|
m.durationCount.Load(),
|
|
runtime.NumGoroutine(),
|
|
ms.Alloc,
|
|
ms.HeapInuse,
|
|
ms.Sys,
|
|
ms.NumGC,
|
|
)
|
|
})
|
|
}
|