Search code examples
javascriptnode.jswinston

Using Morgan and Winston for logging - files are being generated but are blank


Here is my code:

var logDirectory = __dirname + '/log';

//ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

//create a rotating write stream
var accessLogStream = FileStreamRotator.getStream({
filename: logDirectory + '/access-%DATE%.log',
frequency: 'daily',
verbose: false
})

// setup the logger
//app.use(morgan('combined', {stream: accessLogStream}))
app.use(morgan('combined', {stream: logger.stream}))




/*********************************************************************/


//This is 404 for API requests - UI/View 404s should be 
//handled in Angular
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

app.set('port', 5050);
var server = app.listen(app.get('port'), function () {
//debug('Express server listening on port ' + server.address().port);
console.log('Express server listening on port ' + server.address().port);
});

All the necessary dependencies are being reference and the code references a logger.js file which includes the following code:

var winston = require('winston');
winston.emitErrs = true;

var logger = new winston.Logger({
transports: [
    new winston.transports.File({
        level: 'info',
        filename: './logs/all-logs.log',
        handleExceptions: true,
        json: true,
        maxsize: 5242880, //5MB
        maxFiles: 5,
        colorize: false
    }),
    new winston.transports.Console({
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true
    })
],
exitOnError: false
});

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

Files are being generated and the file names are timestamped. Why do my log files have nothing in them?


Solution

  • in place of

    app.use(morgan('combined', {stream: logger.stream}))

    try using

    app.use(morgan('default', { 'stream': logger.stream}));

    This should just write the resource and requested and the Browser Info along with a timstamp to your all-logs.log file.