Menu

Request IDs in Node.js logs with AsyncLocalStorage: trace one request through every await
📰

Request IDs in Node.js logs with AsyncLocalStorage: trace one request through every await

DEV Community: node·Ali Ahmed·17 days ago
#IwPRsiKZ
#devtonodejs#devto#dev#request#context
Long article (905 words) — no AI summary yet.
Reading 0:00
15s threshold

A Node.js server handles many requests at once, so their log lines interleave : "charging card" from one request sits between "start" and "end" of three others, and you can't tell which belongs to which. The fix is a request ID on every log line. Passing it as an argument through every function is noisy and always forgotten somewhere. AsyncLocalStorage , built into Node.js, keeps a value for the duration of one request, across every await , so a logger deep in the call stack can read it. Generate or accept the ID at the edge, validate incoming IDs , return it in a response header, and forward it on outgoing calls so other services' logs join up with yours. Tested with 20 concurrent requests below.

What does AsyncLocalStorage do?

context.run(store, fn) runs fn , and every asynchronous continuation it starts (promises, timers, I/O callbacks) sees the same store through context.getStore() . Two requests running concurrently each see their own store, even though they share one thread.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.