What this thread does
Generate one request ID in middleware and carry it through a request-scoped logger or context in Go slog, FastAPI and Express.
Setup recipe
Do first: set the middleware's JSON field to request_id and its HTTP response header to X-Request-ID. For the minimal examples below always generate a new ID; preserve inbound IDs only under a documented trusted-proxy policy. This is an application design recommendation.
Go slog
Use these imports in a main package: crypto/rand, encoding/hex, log/slog, net/http, os. Register the middleware around a handler accepting a logger:
func withID(next func(http.ResponseWriter, *http.Request, *slog.Logger)) http.Handler {
base := slog.New(slog.NewJSONHandler(os.Stdout, nil))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
http.Error(w, "request ID unavailable", 500)
return
}
id := hex.EncodeToString(b[:])
log := base.With("request_id", id)
w.Header().Set("X-Request-ID", id)
log.InfoContext(r.Context(), "request started", "method", r.Method)
next(w, r, log)
})
}
Pass that log into application helpers. The slog reference documents JSONHandler, With and InfoContext. Supplying a context does not itself turn its values into log attributes; the Go documentation explains context-aware handlers. On current Go, the crypto/rand docs say rand.Read never returns an error and crashes the program if the system random source fails, so the 500 branch is defensive. Checked 2026-10-29.
FastAPI
Put this around an existing app = FastAPI(). Every participating application log must use app_log:
import json
import logging
from contextvars import ContextVar
from uuid import uuid4
request_id = ContextVar("request_id", default=None)
class JsonFormatter(logging.Formatter):
def format(self, record):
data = dict(level=record.levelname, message=record.getMessage(),
request_id=request_id.get())
if record.exc_info:
data["exception"] = self.formatException(record.exc_info)
return json.dumps(data)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
app_log = logging.getLogger("application")
app_log.handlers = [handler]
app_log.propagate = False
app_log.setLevel(logging.INFO)
@app.middleware("http")
async def correlate(request, call_next):
rid = uuid4().hex
reset_key = request_id.set(rid)
try:
app_log.info("request started")
response = await call_next(request)
response.headers["X-Request-ID"] = rid
return response
except Exception:
app_log.exception("request failed")
raise
finally:
request_id.reset(reset_key)
This combines documented FastAPI middleware, Python context variables and a custom logging formatter. Checked 2026-10-28. Server access logs are a separate integration; this example configures application logs.
Express
In a CommonJS application, mount this before routes:
const { AsyncLocalStorage } = require('node:async_hooks');
const { randomUUID } = require('node:crypto');
const scope = new AsyncLocalStorage();
function appLog(message) {
console.log(JSON.stringify({ level: 'info', message,
request_id: scope.getStore()?.request_id ?? null }));
}
app.use((req, res, next) => {
const id = randomUUID();
res.setHeader('X-Request-ID', id);
scope.run({ request_id: id }, () => {
appLog('request started');
next();
});
});
Call appLog from routes, including after await. Express middleware supplies request/response/next; Node documents AsyncLocalStorage.run and randomUUID. Checked 2026-10-28.
Pick by runtime and constraint
| Option | Wins | Loses | Pick this if |
|---|---|---|---|
| slog With and explicit logger arguments | Clear dependency in Go helpers | Helpers can forget the argument | You maintain a Go HTTP service |
| ContextVar plus JSON formatter | Python async context without logger arguments everywhere | Other loggers need integration | You maintain FastAPI |
| AsyncLocalStorage plus JSON serializer | Node async context propagation | Custom callback integrations can lose context | You maintain Express |
These are additions to the existing stable runtime, not reasons to change frameworks. No extra logging package is installed by these snippets; storage, retention and ingestion costs depend on your chosen backend. No backend price or throughput limit is asserted (checked 2026-10-28).
Solo default: the applicable snippet. Small team default: one shared middleware and log helper per runtime. Enterprise default: the same field contract, owned ingress policy and downstream header propagation; request IDs complement your trace IDs.
Verify before rollout
Send overlapping requests and log before and after an awaited operation. Each response ID should match only its own application events. Exercise a failure too. Pass the chosen ID explicitly into outgoing HTTP headers; these snippets do not do that automatically.
Public evidence
In Go issue 58243, jba wrote “putting a logger in a context creates a hidden dependency” (2023-02-02). This is historical API-design evidence supporting the explicit Go logger argument, not a concurrency test of these snippets.
Agent prompt and mistakes
Add correlation to our existing runtime. Show two simultaneous requests retaining distinct IDs after async work, and one exception log with its ID. List any access logs, queues or background tasks that need separate wiring.
Avoid global mutable current IDs, logging authorization headers, and treating a response hook as proof the client received the body.
Limits
These composed examples were not executed. They cover application logs only. Starlette's middleware docs warn that BaseHTTPMiddleware stops ContextVar changes from propagating upwards, so a value set inside a route is not visible after call_next; that the ID set before call_next reaches the route's logs is not stated there and rests on the verify step. Unhandled-error response headers, streaming completion, worker threads, detached jobs and third-party library logs require additional integration. Public evidence does not establish current cross-runtime behaviour.
Started from a post by @Go authors, packaged by the editor. Original post