【问题标题】:Migrating Winston Logger from 2.4.4 to 3.x... The new transports have me lost将 Winston Logger 从 2.4.4 迁移到 3.x... 新的传输让我迷失了方向
【发布时间】:2018-10-25 14:42:06
【问题描述】:

所以我正在尝试从 Winston 2.x 迁移到 3.x,但是它在设置传输方面带来了相当大的转变,而且我似乎无法让它像我之前设置的那样工作,更不用说改进它了。 我在控制台中想要什么

[human-readable-date] [level(colourised)] : [text string], [formatted JSON]

在 2.4 中,我让它打印出未格式化的 JSON,这就足够了,但改进总是很好。

这是我的旧配置文件

const winston = require("winston");
require("winston-mongodb");
const config = require("./mongoDb").config;
const url = config.URL;

const tsFormat = () =>
  `${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`;

const logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      timestamp: tsFormat,
      colorize: true
    }),
    new winston.transports.MongoDB({
      timestamp: tsFormat,
      db: url,
      level: "debug",
      autoReconnect: true
    })
  ]
});
module.exports = logger;

--编辑--

这是我目前所在的地方

const winston = require("winston");
require("winston-mongodb");
const config = require("./");
const mongo = require("./mongo");

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.timestamp({
          format: "YYYY-MM-DD HH:mm:ss"
        }),
        winston.format.align(),
        winston.format.printf(
          info => `${info.timestamp} ${info.level}: ${info.message}`
        )
      )
    }),

    new winston.transports.MongoDB({
      db: `${config.mongoURI}/${config.mongodb}`,
      level: "debug",
      tryReconnect: true,
      storeHost: true
    })
  ]
});
module.exports = logger;

但我根本无法获得所需的 JSON 部分,或者将其发送到 mongodb

【问题讨论】:

    标签: javascript node.js logging winston


    【解决方案1】:

    实现了与我喜欢的本地样式 pino-pretty 相似的结果。

    能够打印出错误堆栈和其他元数据对象。

    代码:

    我为命名空间添加了一个额外的自定义字段,因为我的应用为每个文件创建了一个子记录器,而不是使用 logger.child({ label: namespace }) 公开“根”记录器

    winston.format.combine(
      winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
      winston.format.errors({ stack: true }),
      winston.format.colorize(),
      winston.format.printf(
        ({ timestamp, level, label, message, stack, ...rest }) => {
          const namespace = label ? `(${label})` : ''
          const errStack = stack ? `\n${stack}` : ''
          const meta =
            rest && Object.keys(rest).length
              ? `\n${JSON.stringify(rest, undefined, 2)}`
              : ''
          return `[${timestamp}] ${level}: ${namespace} ${message} ${meta} ${errStack}`
        }
      )
    )
    

    结果:

    【讨论】:

    • 老实说,我已经放弃并坚持使用 2.X!谢谢你,我会在下一个项目中测试它
    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多