Skip to content

Instantly share code, notes, and snippets.

@endeepak
Last active January 12, 2020 15:59
Show Gist options
  • Save endeepak/4b8a07abfdf07964ea85d9cde44e02b9 to your computer and use it in GitHub Desktop.
Save endeepak/4b8a07abfdf07964ea85d9cde44e02b9 to your computer and use it in GitHub Desktop.
NodeJS Request Log Tracing: Express Middleware
const cls = require('cls-hooked');
const generate = require('nanoid/generate');
const alphaNumeric = '0123456789abcdefghijklmnopqrstuvwxyz';
const requestTracingNamespace = cls.createNamespace('request-tracing');
const middleware = () => {
return (req, res, next) => {
requestTracingNamespace.bindEmitter(req);
requestTracingNamespace.bindEmitter(res);
const tracingId = req.header('X-Tracing-Id') || generate(alphaNumeric, 10);
requestTracingNamespace.run(() => {
requestTracingNamespace.set('tracingId', tracingId);
next();
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment