NodeJS Express - Global Unique Request Id

后端 未结 3 1240
萌比男神i
萌比男神i 2020-12-09 10:09

Is it possible to define a unique request Id that is included in each log statement without handing the logger to each method/function call?

Technologies in use: Nod

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 11:00

    At the very beginning of your request handling add something like the following (or put it in its own file):

    var makeID = (function() {
      var index = 0;
      return function() {
       return index++;
      }
    })();
    
    app.use(function(req, res, next) {
      req.id = makeID()
      next()
    })
    

    This will give every request a unique (sequential) id. Do not allow people to identify themselves with it, only use it internally!

    When logging in Winston, you can enter metadata, to be displayed after the message (in the form ${name}=${value}), which looks like this

    app.use(function(req, res) {
      winston.log('info', 'Test Log Message', { id: req.id });
      res.end("Done.")
    });
    

    Hope this is helpful.

提交回复
热议问题