Last active
January 12, 2020 15:59
-
-
Save endeepak/4b8a07abfdf07964ea85d9cde44e02b9 to your computer and use it in GitHub Desktop.
NodeJS Request Log Tracing: Express Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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