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

I am using winston logger. I want to add uuid to every log that has the same uuid for each request.

In app.js

var distributorapp = require('./routes/distributorapp');
app.use('/dstapp',distributorapp);

In routes /distributorapp.js(Middleware)

var qs = require('querystring');
var request = require('request');
var logger = require('../locallibs/logger');
var uuid = require('uuid/v1');
module.exports = {
    mddlw: function (req, res, next) {
        req.bodyData = qs.parse(req.body); // parsing body and added to request object
        req.uuid = uuid(); // Adding uuid to request to available every where throught request
        callHsmRest(req, res); // function to do some logic and handle middleware functionality
    }
};

In logger.js

var winston = require('winston');
var fs = require('fs');
var moment = require('moment');
var today = moment().format('YYYY-MM-DD');

if (!fs.existsSync(today)) {
    fs.mkdirSync(today);
}


function customFileFormatter(options) {
    console.log(options);
    return options.timestamp() + ' [' + options.level.toUpperCase() + '] ' + (undefined !== options.message ? options.message : '') +
            (options.meta && Object.keys(options.meta).length ? JSON.stringify(options.meta) : '');
}

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({
            timestamp: function () {
                return moment().format();
            },
            json: false,
            filename: today + '/test.log',
            formatter: customFileFormatter
        })
    ]
});

Now in every request I want to generate a uuid and add it for the body.So request I added to Middleware. But how will it be available for logger.js in the customFileFormatter formatter?

When someone uses this logger to record any data, I want this uuid to be added to the log formatter in each log through a request.

If someone requires logger.jsand do

logger.info("Hello");
logger.info("Hi");

The following magazines are currently following.

2017-02-24T12: 36: 23 + 05: 30 [INFO] ""
  2017-02-24T12: 36: 23 + 05: 30 [INFO] ""

2017-02-24T12: 36: 23 + 05: 30 [INFO] c00d6800-fa5f-11e6-83c2-f531bfc95472 ""
2017-02-24T12: 36: 23 + 05: 30 [INFO] c00d6800-fa5f-11e6-83c2-f531bfc95472 ""


.

, /dstapp, distributorapp Middleware, dstapp/2017-02-24/test.log
let say /anotherapp, anotherapp Middleware, anotherapp/2017-02-24/test.log

, Advance

+4
3

- ES6 Proxy. requestId app.locals. logger.js :

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);
    }
}

:

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

.

app.js

var logger = require('./locallibs/logger');
app.use(logger)
app.use('/dstapp',distributorapp);

logger.js

var winston = require('winston');
var fs = require('fs');
var moment = require('moment');
var today = moment().format('YYYY-MM-DD');
var uuid = require('uuid/v1');
if (!fs.existsSync(today)) {
    fs.mkdirSync(today);
}


function customFileFormatter(options) {
    return options.timestamp() + ' [' + options.level.toUpperCase() + '] ' + uuid() + ' ' + (undefined !== options.message ? options.message : '') +
            (options.meta && Object.keys(options.meta).length ? JSON.stringify(options.meta) : '');
}

winston.remove(winston.transports.Console);
winston.add(winston.transports.File,
        {
            timestamp: function () {
                return moment().format();
            },
            json: false,
            filename: today + '/test.log',
            formatter: customFileFormatter
        }
);

module.exports = function (req, res, next) {
    next()
};

var logger = require('winston');
logger.info("First Log");
logger.info("Second Log");

2017-02-24T18:51:39+05:30 [INFO] 2cf92c90-fa94-11e6-83ba-ebaf5a4e7acd First Log
2017-02-24T18:51:39+05:30 [INFO] 2cf9c8d0-fa94-11e6-83ba-ebaf5a4e7acd Second Log
+2

. node -uuid uuid - .

1º. , uuid , :

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 °. winston , , :

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 these two pieces of code, you get it. If you want to get a little more in it, you can take a look at this article: https://solidgeargroup.com/express-logging-global-unique-request-identificator-nodejs

+1
source

Source: https://habr.com/ru/post/1670712/


All Articles