Search code examples
node.jswinston

NodeJS Winston not writing in the log file


I'm trying to use Winston to create logs, but it is not writing in the file.

I have the following file in controllers/myControler/myFile.js

const path = require('path');

const winston = require('winston');
const filename = path.join(__dirname, 'testLog.log');
const logger = winston.createLogger({
    transports: [
        new winston.transports.Console({ filename, level: 'error' })
    ]
});

exports.test = async (req, res, next) => {
   logger.log({
      level: 'error',
      message: 'Test'
   });
}

I have the file testLog.log in the root of my project.

When I run the application, I can see in the terminal:

{"level":"error","message":"Test"}

However, the testLog.log file still empty.

Thanks


Solution

  • new winston.transports.Console does not accept filename option.

    You have to append File transport for your logger.

    const logger = winston.createLogger({
      transports: [
        new winston.transports.Console({ level: 'error' }),
        // new line
        new winston.transports.File({ filename, level: 'error' }),
      ]
    });