NodeJS Express - Global Unique Request Id

后端 未结 3 1230
萌比男神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 10:45

    This answer has a problem: the counter goes back to 0 every time the node process is restarted. Turns out there is fairly simple to work around. You simply add an express middleware that tags each request called with a UUID using the uuid package.

    For uuid Pre-2.0

    const uuid = require('uuid');
    const app = express();
    app.use(function (req, next) {
      req.id = uuid.v4();
      next();
    });
    

    For uuid 3.0+

    const uuidv4 = require('uuid/v4');
    const app = express();
    app.use(function (req, next) {
      req.id = uuidv4();
      next();
    });
    

提交回复
热议问题