TypeError: winston.Logger is not a constructor with winston and morgan

Gunjan Patel picture Gunjan Patel · Jun 28, 2018 · Viewed 27.8k times · Source

I tried with Winston for logger. I used in one project their It's working well when I copy paste the code from their to the current existing project than I face an issue like TypeError: winston.Logger is not a constructor

let logger = new (winston.Logger)({ ^

TypeError: winston.Logger is not a constructor

Please guide me, Why this error and what should I have to do for solving this issue.

"morgan": "^1.9.0", "winston": "^3.0.0"

Following is my code in logger.js file.

var appRoot = require('app-root-path');
var winston = require('winston');

var options = {
  file: {
    level: 'info',
    name: 'file.info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 100,
    colorize: true,
  },
  errorFile: {
    level: 'error',
    name: 'file.error',
    filename: `${appRoot}/logs/error.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 100,
    colorize: true,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};


// your centralized logger object
let logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(options.console),
    new (winston.transports.File)(options.errorFile),
    new (winston.transports.File)(options.file)
  ],
  exitOnError: false, // do not exit on handled exceptions
});

Answer

Arif Khan picture Arif Khan · Jun 28, 2018

As you mention, you are using 3.0.0, you can not not use winston.Logger, you may refer library code( https://github.com/winstonjs/winston/blob/master/lib/winston.js#L178 )

You need to make small update in your code, use winston.createLogger instead of new (winston.Logger)

// your centralized logger object
let logger = winston.createLogger({
  transports: [
    new (winston.transports.Console)(options.console),
    new (winston.transports.File)(options.errorFile),
    new (winston.transports.File)(options.file)
  ],
  exitOnError: false, // do not exit on handled exceptions
});