In my express application, I have a module called helpers, which is required in almost all of my routes and modules. This module has a registration method that registers with fluentd (but that doesn't matter). When creating data in a log, I would like to add a unique request identifier so that all logs written for the same request have the same unique identifier. Using the global var at the entry point of the app.use application does not work, because this var will be overwritten every time a new request hits, so the global uuid will change, obviously, it will change in case of high load or long tasks. Res.locals is not available outside of routing, so I cannot use it for this. Is there a way to create a var that will be unique to each request and available in each module, or,perhaps a way to access res.locals data outside of routing? Thanks you
EDIT
Maybe an example will help to better understand the issue. Suppose I have a module called helpers.js:
let helpers = {};
helpers.log = (logData, logName) => {
fluentLogger.emit('', {
name: logName,
message: logData
});
}
module.exports = helpers;
Now, obviously, I can do this at my app.js entry point:
app.use(function (req, res, next) {
res.locals.uuid = uuid.v4();
next();
});
and then in each loaded intermediate module that requires helpers (adding a new parameter to the helpers.log method):
const helpers = require('helpers');
router.post('/', (req, res, next) => {
helpers.log('my log message', 'myLogName', res.locals.uuid);
next();
});
and it works fine. But suppose a large or medium sized project, where there are hundreds of custom modules and models (not middlewares) and a module, may require other modules that require other modules, which finally require the helpers module. In this case, I must pass res.locals.uuid as a parameter for each method of each method so that it is available in the logger method. Not a good idea. Suppose I have a new dbmodel.js module that is required in a middleware function:
const helpers = require('helpers');
let dbmodel = {};
dbmodel.getSomeData = (someParam) => {
helpers.log('my log message', 'myLogName');
}
module.exports = dbmodel;
dbmodel res.locals, , helpers.log .
PHP GLOBAL var , logger .
, :) .
2
CLS. @robertklep . -, ( ) CLS, : https://www.slideshare.net/isharabash/cls-and-asynclistener