0PricingLogin
Go Academy · Lesson

Logging and Request ID Middleware

Structured logging and trace ID injection

Why structured logging?

Plain text logs are hard to parse at scale. Structured logging (JSON or key=value) lets log aggregators (Datadog, Loki, ELK) filter and correlate entries by field.

Request ID generation

Generate a unique ID per request (UUID or ULID) in middleware and attach it to the response header and context:

func RequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-ID")
        if id == "" { id = uuid.New().String() }
        w.Header().Set("X-Request-ID", id)
        ctx := context.WithValue(r.Context(), reqIDKey{}, id)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

All lessons in this course

  1. HTTP Middleware Chain Fundamentals
  2. Logging and Request ID Middleware
  3. Auth and Rate Limiting Middleware
  4. CORS and Panic Recovery Middleware
← Back to Go Academy