Search code examples
javascriptnode.jsloggingwinston

Node logging with Winstonjs logger gives TypeError


I'm just started out with Node and I now want to add some logging to my application, for which Winstonjs seems a perfect fit. So I first installed it:

npm install winston

And then I copied the first example code from the readme (and added the require before it):

"use strict";

let winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    //
    // - Write to all logs with level `info` and below to `combined.log` 
    // - Write all logs error (and below) to `error.log`.
    //
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
// 
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

But I get an error:

/Users/kramer65/mms/testlogging.js:7
    format: winston.format.json(),
                          ^
TypeError: Cannot read property 'json' of undefined

Does anybody know what I'm doing wrong here? All tips are welcome!


Solution

  • Your code is compatible with the new v3 wich is not released yet. If you want to install it :

    npm i winston@next --save
    

    Or if you want to stick with v2, you can read the v2 doc on npm

    ref