Gin in production · 5 MIN READ

Request IDs and access logs in Gin: log the route template and the ID, never the credential

Add request-ID middleware and a structured slog access log that records low-cardinality routes, redacts credentials and can be tested byte for byte.

An access log is what you search during an incident. It is only useful if every line carries the same small set of fields, if one request can be followed across services by an ID, and if the log never becomes a second copy of your users' credentials. Gin's built-in Logger prints raw paths with query strings as text, so production services usually replace it with middleware built on log/slog.

gin · A MAP OF THE IDEA

  1. Accept or generate ID
  2. Run chain with c.Next
  3. Read route + status
  4. Redact, then emit JSON

Useful when

  • One request ID correlates logs, responses and support tickets.
  • Route templates keep log fields low-cardinality and free of secrets.

Watch out

  • ReplaceAttr cannot see inside maps such as a logged http.Header.
  • Recovery registered outside the logger hides panicking requests.

Implementation & operation cost: One JSON line per request plus the storage behind it; sample or drop health probes when volume matters.

01

Accept a request ID only when it is well formed

A request ID ties together the access line, application logs, downstream calls and the screenshot in a customer's bug report. If an edge proxy or calling service already assigned X-Request-ID, reuse it so the trail stays continuous; otherwise generate one. The incoming header is still client input. It can be very long, contain newlines that forge extra lines in text logs, or be chosen to collide with someone else's trail. Accept only a short value from a conservative alphabet and replace anything else. In production, crypto/rand.Text returns 26 base32 characters with at least 128 bits of randomness, enough that collisions are not a concern. Echo the ID in the response header so a client can quote it in a support ticket. If public clients can reach the service directly, consider always generating your own ID and logging the incoming one as a separate field.

02

Request ID, access log and recovery in one chain

The chain is requestID, then accessLog, then recovery. The ID exists before anything logs, and the access log wraps everything after it, so it sees the final status even when a handler panics. Four requests cover a valid incoming ID with a token in the query string, a malicious ID, an unmatched path and a panic. The JSON handler uses test options that make the output stable.

go
package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type requestIDKey struct{}

// validRequestID accepts 8 to 64 characters from a conservative alphabet.
func validRequestID(s string) bool {
	if len(s) < 8 || len(s) > 64 {
		return false
	}
	for _, r := range s {
		ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.'
		if !ok {
			return false
		}
	}
	return true
}

func requestID(generate func() string) gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.GetHeader("X-Request-ID")
		if !validRequestID(id) {
			id = generate()
		}
		c.Set(requestIDKey{}, id)
		c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestIDKey{}, id))
		c.Header("X-Request-ID", id)
		c.Next()
	}
}

func accessLog(log *slog.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()
		route := c.FullPath() // "/notes/:id", never "/notes/42?token=..."
		if route == "" {
			route = "unmatched"
		}
		status := c.Writer.Status()
		level := slog.LevelInfo
		if status >= 500 {
			level = slog.LevelError
		}
		id, _ := c.Get(requestIDKey{})
		log.LogAttrs(c.Request.Context(), level, "request",
			slog.Any("request_id", id),
			slog.String("method", c.Request.Method),
			slog.String("route", route),
			slog.Int("status", status),
			slog.Duration("latency", time.Since(start)),
			slog.Group("headers",
				slog.String("user_agent", c.Request.UserAgent()),
				slog.String("authorization", c.GetHeader("Authorization"))),
		)
	}
}

// redact is the production ReplaceAttr: credentials never reach the sink.
func redact(groups []string, a slog.Attr) slog.Attr {
	switch strings.ToLower(a.Key) {
	case "authorization", "cookie", "set-cookie":
		if a.Value.String() != "" {
			return slog.String(a.Key, "[REDACTED]")
		}
	}
	return a
}

// stableForTest also removes the timestamp and pins latency, the only
// values that change from run to run.
func stableForTest(groups []string, a slog.Attr) slog.Attr {
	if len(groups) == 0 && a.Key == slog.TimeKey {
		return slog.Attr{}
	}
	if len(groups) == 0 && a.Key == "latency" {
		return slog.Duration(a.Key, 0)
	}
	return redact(groups, a)
}

func main() {
	gin.SetMode(gin.TestMode)
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stableForTest}))
	n := 0
	generate := func() string { n++; return fmt.Sprintf("gen-%06d", n) } // production: crypto/rand.Text

	// Recovery sits inside accessLog, so a panic still produces an access line.
	recovery := gin.CustomRecoveryWithWriter(nil, func(c *gin.Context, rec any) {
		id, _ := c.Get(requestIDKey{})
		log.Error("panic recovered", "request_id", id, "panic", fmt.Sprint(rec))
		c.AbortWithStatus(http.StatusInternalServerError)
	})
	r := gin.New()
	r.Use(requestID(generate), accessLog(log), recovery)
	r.GET("/notes/:id", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"id": c.Param("id")}) })
	r.POST("/notes", func(c *gin.Context) { panic("storage adapter bug") })

	send := func(method, target, incomingID string) {
		req := httptest.NewRequest(method, target, nil)
		req.Header.Set("User-Agent", "probe/1.0")
		req.Header.Set("Authorization", "Bearer secret-token-value")
		if incomingID != "" {
			req.Header.Set("X-Request-ID", incomingID)
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Println("->", w.Code, "X-Request-ID:", w.Header().Get("X-Request-ID"))
	}
	send("GET", "/notes/42?token=leaked", "edge-7f3a9c21")
	send("GET", "/notes/43", "bad id\nlevel=ERROR")
	send("GET", "/admin.php", "")
	send("POST", "/notes", "")
}
Read the code

requestID validates the incoming header, falls back to the injected generator, and stores the ID both in Gin's keys and in the request context, so code that only receives a context.Context can find it. accessLog calls c.Next first; after it returns, c.FullPath and c.Writer.Status are final. The first raw URL contained ?token=leaked, yet the line records only /notes/:id. The second ID contained a newline and was replaced with gen-000001. /admin.php matched no route, so FullPath is empty and the line says unmatched. The panic is caught by recovery, logged with the same request ID and turned into a 500, and the access log still records it. redact prints every authorization value as [REDACTED]; stableForTest also drops the time and pins latency to 0 so the output can be compared exactly.

03

Log the route template, not the URL

c.FullPath returns the registered pattern, such as /notes/:id. That keeps the field low-cardinality: you can group, count and alert per route, and the log index does not gain a new value for every note ID. Raw URLs also carry data that should not be stored, such as personal identifiers, email addresses in paths and tokens in query strings. Gin's Logger appends the raw query unless SkipQueryString is set. Unmatched requests are mostly scanners, and logging them under one unmatched value keeps them countable without flooding the index. When you need the concrete resource, log the validated parameter on purpose, for example as a note_id field. Order matters too. If Recovery is registered before the logger, a panic unwinds through the logger before its line is written, and the request you most need to see disappears from the access log.

04

Put redaction in the handler options

Redaction in HandlerOptions.ReplaceAttr applies to every record the logger writes, not only to the call sites a careful author remembered. ReplaceAttr runs for each non-group attribute, including attributes nested in groups, whose names it receives in the groups argument, and returning a zero Attr drops the attribute. It has a limit: it sees attributes, not the inside of values. slog.Any("headers", req.Header) is a single attribute whose value is a map, so a key-based ReplaceAttr never sees the Authorization entry inside it. Log an explicit allow-list of headers instead, or wrap secrets in a type whose LogValue method returns a redacted value. The test options call redact rather than replacing it, so tests run the same redaction code as production.

go
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
	Level:       slog.LevelInfo,
	ReplaceAttr: redact, // real time and latency; credentials still masked
}))
r := gin.New()
r.Use(requestID(rand.Text), accessLog(logger), recovery)
Read the code

This fragment is the production wiring and runs in your own service. crypto/rand.Text already has the func() string shape that requestID expects. Time and latency stay real, and only redact remains in ReplaceAttr. Writing JSON to stdout lets the platform's log collector ship lines without the process managing files or rotation.

05

Carry the ID downstream and test the log contract

Handlers should log through the request context with logger.InfoContext(ctx, ...). The stock JSON handler ignores context values, so either wrap it with a handler that copies request_id from the context into each record, or store logger.With("request_id", id) in the context. Forward X-Request-ID on outbound HTTP calls, plus traceparent if you use OpenTelemetry tracing. Log 5xx at Error and 4xx at Info: client errors are not server incidents, and alerting on them pages someone for every scanner. Health probes usually do not need a line each. Treat the log format as a contract and test it: decode each line as JSON and assert the fields, check that a known secret string never appears in the captured output, check that invalid IDs are replaced, and check that a panic still produces an access line.

TAKE THIS WITH YOU

Accept a well-formed incoming request ID or generate one, log after c.Next with c.FullPath, status, latency and the ID, put redaction in ReplaceAttr so every record passes through it, and register the logger outside Recovery so failed requests are logged too.

Check your understanding

Which value should a Gin access log record as the request path to keep the log searchable and safe?

Go to the source

Progress stays in this browser. No account needed.