How to Correlate Logs with Request IDs in Go

Generate a unique UUID per request, inject it into the context, and log it in handlers to trace requests across your Go application.

Correlate logs with request IDs by generating a unique ID at the start of each request, injecting it into the context, and logging it in every handler.

import (
	"context"
	"log"
	"net/http"
	"github.com/google/uuid"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		reqID := ctx.Value("requestID").(string)
		log.Printf("[%s] Handling request", reqID)
		w.Write([]byte("OK"))
	})

	log.Printf("Server starting with request ID correlation")
	http.ListenAndServe(":8080", middleware(mux))
}

func middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		reqID := uuid.New().String()
		ctx := context.WithValue(r.Context(), "requestID", reqID)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}