How to add uuid in every winston log node js per request?

I had to face this same problem. I found out a solution using node-uuid library to generate a unique uuid for each request, and continuation-local-storage library to share information among modules.

1º. I added a middleware functionality to create the uuid for each request and add it to the namespace I had created:

var uuid = require('node-uuid');
var createNamespace = require('continuation-local-storage').createNamespace;
var myRequest = createNamespace('my request');

// Run the context for each request. Assign a unique identifier to each request
app.use(function(req, res, next) {
    myRequest.run(function() {
        myRequest.set('reqId', uuid.v1());
        next();
    });
});

2º. I wrapped winston library to print get the id of the request and add it to every log, something like this:

var winston = require('winston');
var getNamespace = require('continuation-local-storage').getNamespace;

// Wrap Winston logger to print reqId in each log
var formatMessage = function(message) {
    var myRequest = getNamespace('my request');
    message = myRequest && myRequest.get('reqId') ? message + " reqId: " + myRequest.get('reqId') : message;
    return message;
};

var logger = {
    log: function(level, message) {
        winstonLogger.log(level, formatMessage(message));
    },
    error: function(message) {
        winstonLogger.error(formatMessage(message));
    },
    warn: function(message) {
        winstonLogger.warn(formatMessage(message));
    },
    verbose: function(message) {
        winstonLogger.verbose(formatMessage(message));
    },
    info: function(message) {
        winstonLogger.info(formatMessage(message));
    },
    debug: function(message) {
        winstonLogger.debug(formatMessage(message));
    },
    silly: function(message) {
        winstonLogger.silly(formatMessage(message));
    }
};
module.exports = logger;

With this 2 pieces of code you get it.

To make it easier, I created a library that implements all this, and you can use it as winston, without being worried about all this stuff: https://github.com/davicente/express-logger-unique-req-id

If you want to get into it a little bit more, you can take a look to this article: https://solidgeargroup.com/express-logging-global-unique-request-identificator-nodejs


I did something similar with ES6 Proxy. In middleware I generate unique requestId and add it to app.locals. Then in logger.js I added proxy handler for log functions:

let logProxyHandler = {
    apply (target, thisArg, args) {
        var app = getApp(),
            id = '';
        // Some requests do not have unique ID  
        if (app && app.locals && app.locals.requestId) {
            id = `[${app.locals.requestId}]`;
        }
        args[0] = `${id} ${args[0]}`;
        return Reflect.apply(target, thisArg, args);
    }
}

And then add this:

logger.info = new Proxy(logger.info, logProxyHandler)