Bargain23
Bargain23

Reputation: 1973

How do I make a logger transport to a file using Winston

I need to make a logger transport to a text file that logs errors and warnings. For now, I have a transport for console logging using Winston:

'use strict';

const winston = require('winston');
const m = require('moment-timezone');
let logger = null;

/**
 * Initializes the logger
 * @param {object} configLogging
 */
module.exports.initialize = function initialize(configLogging) {
  const dateFormat = 'dddd, MMMM Do YYYY, h:mm:ss a';

  logger = new winston.Logger({
    transports: [
      new (winston.transports.Console)({
        name: 'info-console',
        level: configLogging.level,
        colorize: true,
        timestamp: function() { return m.utc().format(dateFormat); }
      })
    ]
  });

  logger.info('Starting logging service');
};

/**
 * Gets the logger instance
 * @returns {LoggerInstance} winLogger
 */
module.exports.get = function get() {
  return logger;
};

Upvotes: 4

Views: 10764

Answers (1)

David R
David R

Reputation: 15639

To log your trace in a file try adding the below snippet,

new (winston.transports.File)({ filename: 'somefile.log' });

After adding your your logger assignment should look like,

logger = new winston.Logger({
    transports: [
      new (winston.transports.Console)({
        name: 'info-console',
        level: configLogging.level,
        colorize: true,
        timestamp: function() { return m.utc().format(dateFormat); }
      }),
      new (winston.transports.File)({ filename: 'somefile.log' })
    ]
});

logger.info('Starting logging service');

Update:

For logging Errors and Logs separately Try this,

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      name: 'info-file',
      filename: 'filelog-info.log',
      level: 'info'
    }),
    new (winston.transports.File)({
      name: 'error-file',
      filename: 'filelog-error.log',
      level: 'error'
    })
  ]
});

Hope this helps!

Upvotes: 4

Related Questions