18
votes

I followed a tutorial to set up winston (2.x) default logger in my express app. When updating to the current version of winston (3.0.0) I have a problem with adding the transports. I have followed the latest docs but still I get the notice in console and no log files are created at all:

[winston] Attempt to write logs with no transports

logging.js

const winston = require('winston');

module.exports = function () {

  const files = new winston.transports.File({ filename: 'logfile.log' });
  const myconsole = new winston.transports.Console();

  winston.add(myconsole);
  winston.add(files);

}

index.js

const winston = require('winston');
...

require('./logging');
winston.info("Give some info");

[winston] Attempt to write logs with no transports {"message":"Give some info","level":"info"}

What am I doing wrong?

4

4 Answers

4
votes

I also had a similar issue. If I recall correctly, I had to call the requirement as a function in my index.js.

require('./logging')();
17
votes

In winston 3 you need to create a logger object, then add transports to it.

Winston 3 has many examples, but to adapt from the readme, do something like this:

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'logfile.log' })
  ]
});

logger.info('it works!!');
8
votes

If you want to use the default logger in winston v3 then you simply have to add this piece of code in your main file

const winston = require('winston')

winston.add(new winston.transports.File({ filename: 'logfile.log' }))
1
votes

I had the same issue and by just looking at the documentation, I was able to write logs in a file by just adding the below code.

1. create a file logger.js and paste the below code

// => logger.js
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [   
  new winston.transports.File({ filename: 'error.log', level: 'error' }),
  new winston.transports.File({ filename: 'combined.log' })
]
});

if (process.env.NODE_ENV !== 'production') {
   logger.add(new winston.transports.Console({
   format: winston.format.simple()
   }));
}

// just add the below to write into a file
winston.add(logger);

2. require it into your app.js file

// => app.js
require('./middlewares/logger');

3. Test it by just writing the below code inside a function of one of your endpoints.

     router.get('/', async (req, res) => {
       throw new Error('Resource not found');  
       res.send({ error: 'Resource not found' });
     }); 

Et Voila ça marche. Go inside your error log file to find this message there.

{"message":"500 - Resource not found - /api/genres - GET - ::1","level":"error"}