Daniel McCrevan
Daniel McCrevan

Reputation: 179

Winstonjs printing json to console

logger.js

var winston = require('winston');

var logger = new winston.createLogger({
    transports: [
        new winston.transports.Console({
            level: 'info',
            handleExceptions: true,
            json: false,
            colorize: true,
            timestamp: true
        }),
        new winston.transports.Console({
            level: 'error',
            handleExceptions: true,
            json: false,
            colorize: true,
            timestamp: true
        }),
    ],
    exitOnError: false
});

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

Whenever I call logger.info or logger.error, it'll log a json object to the screen without colors. What is wrong with my logger that is causing this issue? The timestamp isn't printing on this as well.

Upvotes: 0

Views: 1314

Answers (1)

Mika Sundland
Mika Sundland

Reputation: 18939

Looks like you are mixing the old syntax with the v3 syntax. According to the documentation you can write it something like this:

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf, colorize } = format;

const myFormat = printf(info => {
  return `${info.timestamp} ${info.level}: ${info.message}`;
});

const logger = createLogger({
   format: combine(
    colorize(),
    timestamp(),
    myFormat
  ),
  transports: [
    new transports.Console({
        level: 'info',
        handleExceptions: true
    }),
    new transports.Console({
        level: 'error',
        handleExceptions: true
    }),
  ],
  exitOnError: false
});

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

This will show timestamps and colors.

Logger output

There is also an upgrade guide here that shows the differences between v2 and v3.

Upvotes: 2

Related Questions