Request tracking request by ID in node.js

In my node.js application, whenever I receive a request, I want to "stamp" it with some unique identifier and be able to track all the actions (log statements) associated with this request using this identifier. Therefore, when a request arrives, and I transfer it to lower the levels of applications (services, database calls, etc.), I want to be able to collect all the logs corresponding to this request identifier to restore my path through the application.

So, having this picture, I now use request-local , but it does some kind of heavy magic that just hit me (the logs from several requests get the same identifier).

The code is mostly based on Promises (and not on the old old node callbacks), and I use higher order functions to provide dependencies on my actual functions (with creating an application tree at startup).

The first and quite obvious solution is to pass this request identifier to each function called, but this is a disaster, and I'm not going to do it.

How do you (reliably) perform such request tracking without explicitly passing this id / context as an additional argument for all functions down?

+4
source share
2 answers

, , - (req, id...) . , node -uuid (- ), , ( ). , Winston, . .

https://solidgeargroup.com/express-logging-global-unique-request-identificator-nodejs

+3

, , , - , . , , , - ( randomstring). , , . , res.locals( ) :

//middleware flow.js
var random = require('randomstring');

var generate = function(){
    var dt = new Date();
    return random.generate() + dt.toISOString();
}
module.exports.createID = function(req, res, next){
    //store flowid in res - this hold state over the request life time
    res.locals.flowid = generate();
    next();
}

, :

var flowcontrol = require('flow.js');
var middleware = require('middleware.js');

app.use(flowcontrol.createID);

//route example
app.get('/api/awesomeresource', middlewares.first, middlewares.second);

, , :

//middleware.js
module.exports.first = function(req, res, next){
   console.log(res.locals.flowid + " - First i did this...");
   //your logic here
   next();
}
module.exports.second = function(req, res, next){
   console.log(res.locals.flowid + " - Second i did this...");
   //your logic here before the response
   res.sendStatus(200);
}

GET /api/awesomeresource HTTP/1.1 :

> R90A56nEmZWYK73NOEVbWv2RS6DolO4D2017-12-07T10:29:39.291Z - First i did
> this... 
> R90A56nEmZWYK73NOEVbWv2RS6DolO4D2017-12-07T10:29:39.291Z -
> Second i did this...

, -.

0

Source: https://habr.com/ru/post/1665228/


All Articles