How to log request and transaction id in each log line using winston for Node JS?

I created the Node JS REST service using Express. Each request that lands on this service has headers, such as "X-org-ReqId" and "X-org-Tid", which I need to log all the log lines that are written during this request. Basically, I need to write some contextual information to each line of the log to help me track transactions / requests across multiple services.

I am using winston logger initialized as follows:

var winston = require('winston');
var appLogger = new(winston.Logger)({
  transports: [
    new(winston.transports.Console)({
        level: 'info', //TODO: Should be changed to Error in prod
        colorize: true
    }),
    new(winston.transports.DailyRotateFile)({
        filename: '/var/log/org/my-service.log',
        datePattern: '.yyyy-MM-dd',
        tailable: true,
        // handleExceptions: true,
        json: true,
        logstash: true
    })
  ],
  exitOnError: false
});

appLogger.on('error', function(err) {
  console.error("Logger in error", err);
});

module.exports.logger = function() {
  return appLogger;
};

and in separate classes, wherever I want to use it, I like the following:

var logger = require('../config/logger').logger();

myObject.on("error", function (err) {
                logger.error("Error connecting bucket=" + bucketId , err);
});

This will create the log as follows:

{"level":"info","message":"Error connecting bucket=2.....","timestamp":"2015-06-10T06:44:48.690Z"}

Winston timestamp , , req.headers ['X-org-ReqId'] req.headers ['X-org-Tid'], , .

, :

{"level":"info","message":"Error connecting bucket=2....","timestamp":"2015-06-10T06:44:48.690Z", "tid":"a3e8b380-1caf-11e5-9a21-1697f925ec7b", "reqid":"aad28806-1caf-11e5-9a21-1697f925ec7b"}

java- NDC, Node JS?

+4
1

, . , -, "req", .

- :)

winston "log.js":

// MyLogger definition
function MyLogger() {
    this.__proto__.__proto__.constructor.apply(this, arguments);
}

// Inheritance
MyLogger.prototype.__proto__ = winston.Logger.prototype;

// Overwriting methods
MyLogger.prototype.log = function() {
    var args = [];
    // Copying arguments not to modify them
    for (var i = 0; i < arguments.length; i++) {
        args[i] = arguments[i];
    }

    // Adding information in logs
    var lastArg = args[arguments.length - 1];
    if (typeof lastArg === 'object'
        && lastArg.headers) {
        args[arguments.length - 1] = {
            // Liste des infos ajoutées dans les logs
            requestId: lastArg.headers['x-request-id'] ? lastArg.headers['x-request-id'] : arguments[arguments.length - 1].id,
            host: arguments[arguments.length - 1].headers.host,
            pId: process.pid
        };
    }

    // Calling super
    this.__proto__.__proto__.log.apply(this, args);
}

MyLogger.prototype.error = function() {
    var args = ["error"];
    for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
    }
    this.__proto__.log.apply(this, args);
}
MyLogger.prototype.warn = function() {
    var args = ["warn"];
    for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
    }
    this.__proto__.log.apply(this, args);
}
MyLogger.prototype.info = function() {
    var args = ["info"];
    for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
    }
    this.__proto__.log.apply(this, args);
}
MyLogger.prototype.verbose = function() {
    var args = ["verbose"];
    for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
    }
    this.__proto__.log.apply(this, args);
}
MyLogger.prototype.debug = function() {
    var args = ["debug"];
    for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
    }
    this.__proto__.log.apply(this, args);
}
MyLogger.prototype.silly = function() {
    var args = ["silly"];
    for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
    }
    this.__proto__.log.apply(this, args);
}

var logger = new MyLogger({
    transports: [
        new winston.transports.File({
            level: config.LOG_LEVEL,
            filename: config.LOG_FILE,
            handleExceptions: true,
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: config.LOG_LEVEL,
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
     exitOnError: false
});

module.exports                  = logger;

, :

var logger          = require("../log.js");

...

logger.debug("My message", req);

JSON , .

"req" ​​ .

, :)

0

All Articles