【问题标题】:log json with date and time format with winston node logger使用 winston 节点记录器以日期和时间格式记录 json
【发布时间】:2022-01-12 06:58:02
【问题描述】:

我正在尝试使用包含时间戳的 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 格式,而不是消息。

【问题讨论】:

  • 我不清楚你想要达到什么目标。想要以 json 格式粘贴日志吗?
  • @KarlR 我已经更新了问题,让我知道是否更好。

标签: node.js winston


【解决方案1】:

您可以使用 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')
})

当您使用GET HTTP 方法请求localhost:8080 时,将导致:

{"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
  • 不需要format.simple(),因为它只是另一种类型(字符串文字),更多信息请参见doc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2018-09-15
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    相关资源
    最近更新 更多