In my node.js application whenever I get request I'd like to "stamp" it with some unique ID and be able to track all the activities (log statements) related to this request by this ID. So when request comes in and I pass its handing to lower application layers (services, database calls etc) I want to be able to collect all logs matching given request ID to rebuild its journey through the app.
So having this picture, I use request-local module now, but it does some heavy magic that has just failed me (logs from multiple requests get the same ID).
The code is mostly based on Promises (not plain old node callbacks) and I use higher order functions to provide dependencies to my actual functions (with application tree being built during the start).
First and quite obvious solution would be to pass this request ID down to every function called, but it's a disaster and I'm not gonna do that.
How do you (reliably) do that kind of request tracking without explicitly passing this id/context as an extra argument to functions all levels down?
I believe that what you're looking for is a logic flow id, which should be unique and generated upon every new request kicking in on your backend. If this assumption is correct, what I normally do is to create a middleware on my express router to generate a new and random flow id (with randomstring). To be sure that this flow id is unique, i add the timestamp to that. In order to pass this flow id to the next middlewares we should store it under res.locals (here the documentation ) Your middleware could look like this:
Now we can inject this middleware on the app using:
Using this approach, you will be able to log the same flow id on every middleware like:
The result of
GET /api/awesomeresource HTTP/1.1
will be the following console log:Which means that you can then track some sort of log files by this stamp and debug your backend logic if needed.
Cheers