Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 355
Bargain23 Avatar asked Sep 06 '25 15:09

Bargain23


1 Answers

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!

like image 54
David R Avatar answered Sep 09 '25 04:09

David R