Winstonjs将json打印到控制台

时间:2018-01-28 07:09:37

标签: node.js logging winston

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);
    }
};

每当我调用logger.infologger.error时,它都会将json对象记录到屏幕上而没有颜色。导致此问题的记录器有什么问题?时间戳也不打印在此。

1 个答案:

答案 0 :(得分:2)

看起来您正在将旧语法与v3语法混合使用。根据{{​​3}},您可以这样写:

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);
    }
};

这将显示时间戳和颜色。

documentation

还有一个升级指南Logger output,其中显示了v2和v3之间的差异。