---
title: "Go HTTP Server"
description: "Logging, metrics, and tracing wired together for a Go HTTP server with trace_id correlation across all three signals."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Go HTTP Server

The three observability signals are most useful when they reference each other.
A spike in your p99 latency metric leads you to a slow trace; that trace's
`trace_id` pulls up the exact log lines from the request. This page wires all
three together for a Go HTTP server.

## Setup

Initialize the three signals once at startup and pass them down explicitly.

### Logger

```go
func newLogger() *slog.Logger {
    level := slog.LevelInfo
    if os.Getenv("LOG_LEVEL") == "debug" {
        level = slog.LevelDebug
    }
    return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
        Level: level,
    })).With(
        "service", "my-service",
        "version", os.Getenv("APP_VERSION"),
    )
}
```

### Tracer

```go
func setupTracing(ctx context.Context) (func(context.Context) error, error) {
    exp, err := otlptracehttp.New(ctx) // reads OTEL_EXPORTER_OTLP_ENDPOINT
    if err != nil {
        return nil, err
    }
    tp := sdktrace.NewTracerProvider(
        sdktrace.WithBatcher(exp),
        sdktrace.WithResource(resource.NewWithAttributes(
            semconv.SchemaURL,
            semconv.ServiceName("my-service"),
        )),
        sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(0.1))),
    )
    otel.SetTracerProvider(tp)
    otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
        propagation.TraceContext{},
        propagation.Baggage{},
    ))
    return tp.Shutdown, nil
}
```

### Metrics

```go
var (
    httpRequestsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Total number of HTTP requests.",
    }, []string{"method", "status", "handler"})

    httpRequestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
        Name:    "http_request_duration_seconds",
        Help:    "HTTP request duration in seconds.",
        Buckets: prometheus.DefBuckets,
    }, []string{"method", "status", "handler"})

    httpRequestsInFlight = prometheus.NewGaugeVec(prometheus.GaugeOpts{
        Name: "http_requests_in_flight",
        Help: "Current number of in-flight HTTP requests.",
    }, []string{"method"})
)

func newRegistry() *prometheus.Registry {
    reg := prometheus.NewRegistry()
    reg.MustRegister(httpRequestsTotal, httpRequestDuration, httpRequestsInFlight)
    return reg
}
```

## Middleware

Three middlewares, applied outermost-first: tracing → logging → metrics.

Tracing must be outermost so the span exists in context when the logging
middleware runs. The logging middleware reads the active span to inject
`trace_id` into every log line; that injection is the key correlation point.

### Helper: `statusWriter`

Both middlewares need the response status code after the handler runs:

```go
type statusWriter struct {
    http.ResponseWriter
    status int
}

func (w *statusWriter) WriteHeader(code int) {
    w.status = code
    w.ResponseWriter.WriteHeader(code)
}
```

### Tracing middleware

Use the OTEL contrib package; it handles `traceparent` extraction, span
creation, and W3C header propagation automatically:

```go
import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

handler = otelhttp.NewHandler(handler, "server")
```

### Logging middleware

The integration point: pull `trace_id` and `span_id` from the active span
(created by `otelhttp` earlier in the chain) and bake them into the
request-scoped logger. Every log line from this request, in the middleware
and in handlers, automatically carries both IDs.

```go
type loggerKey struct{}

func loggingMiddleware(base *slog.Logger, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log := base.With("method", r.Method, "path", r.URL.Path)

        if sc := trace.SpanFromContext(r.Context()).SpanContext(); sc.IsValid() {
            log = log.With(
                "trace_id", sc.TraceID().String(),
                "span_id",  sc.SpanID().String(),
            )
        }

        start := time.Now()
        rw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
        ctx := context.WithValue(r.Context(), loggerKey{}, log)
        next.ServeHTTP(rw, r.WithContext(ctx))

        log.Info("request",
            "status",      rw.status,
            "duration_ms", time.Since(start).Milliseconds(),
        )
    })
}

func loggerFromCtx(ctx context.Context) *slog.Logger {
    if log, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok {
        return log
    }
    return slog.Default()
}
```

### Metrics middleware

```go
func metricsMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        method := r.Method

        httpRequestsInFlight.WithLabelValues(method).Inc()
        defer httpRequestsInFlight.WithLabelValues(method).Dec()

        start := time.Now()
        rw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
        next.ServeHTTP(rw, r)

        // r.Pattern is set by ServeMux during routing; read it after ServeHTTP.
        handler := r.Pattern
        if i := strings.IndexByte(handler, ' '); i >= 0 {
            handler = handler[i+1:] // strip "GET " prefix
        }

        status := strconv.Itoa(rw.status)
        httpRequestsTotal.WithLabelValues(method, status, handler).Inc()
        httpRequestDuration.WithLabelValues(method, status, handler).Observe(time.Since(start).Seconds())
    })
}
```

## Wiring it up

```go
func main() {
    ctx := context.Background()

    logger := newLogger()

    shutdown, err := setupTracing(ctx)
    if err != nil {
        logger.Error("failed to initialize tracing", "err", err)
        os.Exit(1)
    }
    defer shutdown(ctx)

    reg := newRegistry()

    mux := http.NewServeMux()
    mux.HandleFunc("GET /users/{id}", handleGetUser)
    mux.HandleFunc("POST /users", handleCreateUser)

    // Expose Prometheus metrics on a separate port so it's not public-facing.
    go func() {
        metricsMux := http.NewServeMux()
        metricsMux.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
        http.ListenAndServe(":9090", metricsMux)
    }()

    // Middleware chain: tracing → logging → metrics → mux
    var handler http.Handler = mux
    handler = metricsMiddleware(handler)
    handler = loggingMiddleware(logger, handler)
    handler = otelhttp.NewHandler(handler, "server")

    srv := &http.Server{Addr: ":8080", Handler: handler}
    logger.Info("server starting", "addr", srv.Addr)
    if err := srv.ListenAndServe(); err != nil {
        logger.Error("server stopped", "err", err)
    }
}
```

### Using the logger in handlers

Handlers retrieve the request-scoped logger from context. It already carries
`trace_id`, `span_id`, `method`, and `path`; no manual threading needed:

```go
func handleGetUser(w http.ResponseWriter, r *http.Request) {
    log := loggerFromCtx(r.Context())
    id  := r.PathValue("id")

    user, err := db.GetUser(r.Context(), id)
    if err != nil {
        log.Error("failed to fetch user", "err", err, "user_id", id)
        http.Error(w, "internal error", http.StatusInternalServerError)
        return
    }

    log.Info("user fetched", "user_id", id)
    json.NewEncoder(w).Encode(user)
}
```

## What you get

Every request produces correlated signals across all three backends.

**Log line** (JSON, one per request):

```json
{
  "time": "2024-01-15T10:30:00.123Z",
  "level": "INFO",
  "msg": "request",
  "service": "my-service",
  "version": "1.4.2",
  "method": "GET",
  "path": "/users/f47ac10b",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "status": 200,
  "duration_ms": 54
}
```

**Metric series** (Prometheus):

```
http_requests_total{method="GET", status="200", handler="/users/{id}"} 1
http_request_duration_seconds_bucket{handler="/users/{id}", le="0.1"} 1
```

**Trace** (Jaeger / Tempo / Honeycomb):

```
trace_id: 4bf92f3577b34da6a3ce929d0e0e4736

[GET /users/{id}       ] 0ms–54ms
  [db.GetUser          ] 2ms–51ms
```

The `trace_id` in the log line is the same ID in the trace. Most log aggregators
(Grafana, Datadog, Honeycomb) can turn it into a direct link to the trace view.

:::tip
When a metric alert fires, the usual path is: metric → trace (find a slow example) → logs (read
the full event context). `trace_id` is the join key between the last two steps.
:::

Source: https://codex.mirio.dev/observability/http-server/index.mdx
