Search code examples
node.jswinston

How to add session id to each log in winston logger


In my node application I'm using winston module to store my application logs. I am getting the log as:

2017-11-22T07:16:38.632Z - info: asset type is attached successfully

Now I want to add sessionID after timestamp. I want my log as:

 2017-11-22T07:16:38.632Z -**sessionId here**- info: asset type is attached successfully.

My code which I used for winston logging is:

var winston = require('winston');
require('winston-daily-rotate-file');
const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  verbose: 4,
  debug: 5,
  silly: 6,
  trace: 7
};

var transport = new (winston.transports.DailyRotateFile)({
  filename: 'logs/./log',
  datePattern: 'yyyy-MM-dd.',
  prepend: true,
  json: false,
  level: process.env.ENV === 'development' ? 'debug' : 'info'
});

var logger = new (winston.Logger)({
  levels: levels,
  transports: [
    transport
  ]
});

module.exports = logger;

Solution

  • You have to custom the log format https://github.com/winstonjs/winston/tree/2.x#custom-log-format

    First update your transport :

    var transport = new (winston...
      ...
      level: process.env.ENV === 'development' ? 'debug' : 'info',
      timestamp: () => {
        let today = new Date();
        return today.toISOString();
      },
      formatter: options => `${options.timestamp()} -${options.meta.sessionId}- ${options.level}: ${options.message}`
    });
    

    Then, just pass the session ID to your logger meta feature :

    logger.info('asset type is attached successfully', {sessionId: 'mySessionID'});

    and you get

    2017-11-22T14:13:17.697Z -mySessionID- info: asset type is attached successfully

    Edit : instead of exporting only the winston.logger object, we export an object which requires a sessionId as a parameter, and contains the winston.logger. We also update the transport, so we customize its formatter property in the new Logger object. In the formatter property, we replace the meta declaration with the new this.sessionId variable, so we don't use the meta property anymore.

    logger.js :

    var transport = new (winston...
      ...
      level: process.env.ENV === 'development' ? 'debug' : 'info',
      timestamp: () => {
        let today = new Date();
        return today.toISOString();
      }
    });
    
    class Logger {
      constructor(session) {
        this.sessionId = session;
        this.transport = transport;
        this.transport.formatter = options => `${options.timestamp()} -${this.sessionId}- ${options.level}: ${options.message}`;
        this.logger = new (winston.Logger)({
          levels: levels,
          transports: [this.transport]
        });
      }
    }
    
    module.exports = Logger;
    

    server.js :

    const Logger = require('./logger.js');
    let logman = new Logger('my_session_id');
    let logger = logman.logger;
    

    logger.info('asset type is attached successfully');

    2017-11-23T13:13:08.769Z -my_session_id- info: asset type is attached successfully