How to identify request (by ID) through middleware chain in Express.
express, logging, node.js
Solution
You can use `req` object that does comes with every request in express. So the first route you would do in your application would be:
var logIdIterator = 0;
app.all('*', function(req, res, next) {
req.log = {
id: ++logIdIterator
}
return next();
});
And then anywhere within express, you can access that `id` in `req` object: `req.log.id`; You will still need to pass some data into functions that do want to create some logs. In fact you might have logging function within `req.log` object, so that way it will be guaranteed that logging will happen only when there is access to `req.log` object.
Problem
I am developping a RESTful server in node.js, using Express as framework, and Winston, for the moment, as logger module. This server will handle a big amount of simultaneous request, and it would be very useful to me to be able to track the log entries for each specific request, using something like a 'request ID'. The straight solution is just to add this ID as another piece of logging information each time I want to make a log entry, but it will mean to pass the 'request ID' to each method used by the server. I would like to know if there is any node.js/javascript module or technique that would allow me to do this in an easier way, without carrying around the request ID for each specific request.