Winston is not writing logs to files
Asked Answered
C

3

8

I made two transports for errors and warnings in Winston that supposedly writes to files. The existing transport for console logging works fine, and I did check pm2 logs and saw the logs, but the transports for files are not saving anyting.

'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); }
      }),
      new (winston.transports.File)({
        name: 'warning-file',
        filename: 'warning-file.log',
        level: 'warning'
      }),
      new (winston.transports.File)({
        name: 'error-file',
        filename: 'error-file.log',
        level: 'error'
      })
    ]
  });

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

/**
 * Gets the logger instance
 * @returns {LoggerInstance} winLogger
 */
module.exports.get = function get() {
  return logger;
};
Cuff answered 10/10, 2017 at 3:6 Comment(3)
I will suggest to manually create error-file.log & warning-file.log file with write permission to test Winston logging. If it works then it's not Winston issue, provide proper read/write/execute access to the directory in which your app is present for the current user.Exhaustive
I did test the logger in my local computer, and it's working fine, but for some reason it's not working in the server @ExhaustiveCuff
In addition, you must let the application create the log files with its own permissions. Take care that your log rotation solution does not recreate the active log file. It should only copy the content to an archive and clean the active file. Otherwise the file ID is changed and logging fails.Seashore
S
7

please create one log.js file and write this all code

var winston = require('winston');
const env = process.env.NODE_ENV;
const logDir = 'logs';
const fs = require('fs');

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

const now = new Date();
var logger = new(winston.Logger)({
transports: [

    new winston.transports.File({
        name: 'error-file',
        filename: './logs/exceptions.log',
        level: 'error',
        json: false
    }),

    new(require('winston-daily-rotate-file'))({
        filename: `${logDir}/-apimodules.log`,
        timestamp: now,
        datePattern: 'dd-MM-yyyy',
        prepend: true,
        json: false,
        level: env === 'development' ? 'verbose' : 'info'
    })
],
exitOnError: false
});

module.exports = logger;
module.exports.stream = {
  write: function(message, encoding) {
    logger.info(message);
    console.log('message=', message);
  }
};

For add log, use this file everywhere that need to log using this code

var logger = require('./path of/log.js');
logger.info('*** Requested for First log... ***');
Sexless answered 10/10, 2017 at 4:27 Comment(3)
While your solution works, you don't explain why it works. :/ It would be more than useful to know.Halmstad
var logger = winston.createLogger({ instead of var logger = new(winston.Logger)({Matrimonial
I am facing the same problem. so i change my code according to your solution but getting error as explained. when I use new(winston.Logger) it gives me error that TypeError: winston.Logger is not a constructor.Tympanic
B
2

For modernization, here is the working code for the above answer as the above answer does not work for the latest version of winston 3.2.1. This is the working code for the file log.js

const fs = require('fs');

var winston = require('winston');

const env = process.env.NODE_ENV;
const logDir = 'logs';

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

const now = new Date();
var logger = winston.createLogger({
  transports: [
    new winston.transports.File({
      name: 'error-file',
      filename: './logs/exceptions.log',
      level: 'error',
      json: false,
    }),

    new (require('winston-daily-rotate-file'))({
      filename: `${logDir}/-apimodules.log`,
      timestamp: now,
      datePattern: 'dd-MM-yyyy',
      prepend: true,
      json: false,
      level: env === 'development' ? 'verbose' : 'info',
    }),
  ],
  exitOnError: false,
});

module.exports = logger;

module.exports.stream = {
  write: function (message) {
    logger.info(message);
    console.log('message = ', message);
  },
};

Note that this outputs the data to a root folder named logs.

Bell answered 9/5, 2020 at 16:5 Comment(0)
C
0

For "winston": "^3.7.2"

winston.add(new winston.transports.File({
    name: 'error-file',
    filename: './logs/exceptions.log',
    level: 'error',
    json: false
}))
Complect answered 8/6, 2022 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.