Search code examples
node.jsloggingwinston

Winston logging in console but not in the log files


I'm using Winston for logging in my project. I can see the logs in the console but there is no logging inside the log files.

Winston.js file

var appRoot = require('app-root-path');
var winston = require('winston');
const {transports, createLogger, format} = require('winston');
winston.addColors( winston.config.npm.colors );

const logger = winston.createLogger({
level: 'info',
format: format.combine(
    format.timestamp({format:'MM-YY-DD hh:mm:ss a'}),
    format.json(),

),
transports: [
  new winston.transports.File({ filename: './logs/error.log', level: 'error' }),
  new winston.transports.File({  handleExceptions: true,colorize:true,
    json: true,filename: './logs/app.log',
})
]
  });
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
  format: winston.format.simple()
}));
  }
module.exports = logger;

Server.js code

var morgan = require('morgan');
var winston = require('./server/config/winston');

Node version 8.11.3

Winston version 3.1.0


Solution

  • You need to make sure 'logs' folder exists. Winston doesnt take care of non-existent folder, nor giving any warning or errors.

    You can put following code in your server.js

    var fs = require( 'fs' );
    var logDir = 'logs';
    if ( !fs.existsSync( logDir ) ) {
       fs.mkdirSync( logDir );
    }
    winston.info('Hey NODE');
    

    Using the absolute folder path inside the winston.js solved the problem.