使用Winston节点记录器以日期和时间格式记录json

时间:2018-08-22 21:10:24

标签: node.js winston

我正在尝试使用包含时间戳记的winston登录json,我具有以下配置:

'use strict';

import * as winston from 'winston';

const LOG = !!process.env.LOG;

export const { error, info, debug } = winston.createLogger({
  transports: [new winston.transports.Console()],
  silent: process.env.NODE_ENV === 'test' && !LOG,
  format: winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    winston.format.colorize({ all: true }),
    winston.format.simple()
  )
});

但是它正在记录这样的消息:

info: connecting /closebanner {"timestamp":"2018-08-22 22:09:35"}

只有时间戳是json格式,而不是消息。

1 个答案:

答案 0 :(得分:0)

您可以使用winston json格式化程序:

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

const logger = createLogger({
  format: combine(
    timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    json(),
  ),
  transports: [new transports.Console()]
})

例如:

app.get('/', (req, res) => {
  logger.info('request came');
  logger.error({ "errorMessage": "something went wrong " })
  return res.status(500).end();
})

app.listen(8080, () => {
  logger.info('app started')
})

使用localhost:8080 HTTP方法请求GET时,结果为:

{"message":"app started","level":"info","timestamp":"2018-08-23 00:56:48"}
{"message":"request came","level":"info","timestamp":"2018-08-23 00:56:54"}
{"message":{"errorMessage":"something went wrong"},"level":"error","timestamp":"2018-08-23 00:56:54"}

请注意:

  • colorize不适用于JSON-检查github discussion
  • 不需要简单,因为它只是logform的类型-字符串文字,并且您想在doc此处使用JSON
相关问题