Here is a revised solution using the continuation-local-storage
module.
Here is my context
module. So far it only stores path, request time and correlation ID that it generates if it doesn’t receive one in the request.
'use strict';
const continuation = require('continuation-local-storage');
const cuid = require('cuid');
const appName = require('config').get('app_name');
class Context {
static setup(req, res, next) {
const session = continuation.createNamespace(appName);
session.run(() => {
session.set('context', new Context(req));
next();
});
}
constructor(req) {
this.path = req.path;
this.corrId = req.headers['x-correlation-id'] || cuid();
this.requestTime = Date.now();
}
static current() {
return continuation.getNamespace(appName).get('context');
}
}
module.exports = Context;
My app.js
includes:
const Context = require('./context');
app.use(Context.setup);
After that, any code can call Context.current()
to get the current context of the Express request. I will use that for consistent logging.