【问题标题】:Why winston logs the error message twice in the same error?为什么winston 在同一个错误中记录错误消息两次?
【发布时间】:2020-02-24 03:28:28
【问题描述】:

编辑:显然这是 winston 的一个已知问题:https://github.com/winstonjs/winston/issues/1739

我有一个将日志保存在文件中的节点服务器、一个 mongoDB 并在开发时在控制台中显示它们。

当我抛出错误时:

throw new Error("The error message.");

winston 记录错误如下:

2020-02-24 12:20:19 - error: "The error message.The error message."

如您所见,消息字符串是重复的。为什么?我所有的日志都有相同的重复问题。

我尝试使用该格式,但无济于事。任何帮助表示赞赏!

我的代码:

const { createLogger, format, transports } = require("winston");
require("winston-mongodb");
require("express-async-errors");

// Manually throwing the exception will let winston handle the logging
process.on("unhandledRejection", (ex) => {
  throw ex;
});

// Log to files
const logger = createLogger({
  level: "verbose",
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    format.errors({ stack: true }),
    format.splat(),
    format.json()
  ),
  transports: [
    new transports.File({filename: "./logs/combined.log", level: "verbose"}),
  ],
  transports: [
    new transports.File({filename: "./logs/error.log", level: "error"}),
    new transports.File({filename: "./logs/combined.log"}),
  ],
  exceptionHandlers: [
    new transports.File({ filename: "./logs/exceptions.log" }),
    new transports.File({ filename: "./logs/combined.log" }),
  ],
  handleExceptions: true,
});

// Log to database
logger.add(new transports.MongoDB({
  db: "mongodb://localhost:27017/rest-api-mongodb",
  options: {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  },
  metaKey: "stack",
}));

// This is used to make the console logging more readable
// Enabled only in development
if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === undefined) {
  const consoleFormat = format.printf(function(info) {
    //console.log(info);
    return `${info.timestamp} - ${info.level}: ${JSON.stringify(info.message, null, 4)}`;
  });

  logger.add(new transports.Console({
    format: format.combine(
      format.colorize(),
      format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
      }), consoleFormat),
    level: "debug",
    handleExceptions: true,
    colorize: true,
    prettyPrint: true
  }));
}

module.exports = logger;

【问题讨论】:

    标签: node.js logging winston


    【解决方案1】:

    在调用 winston.error 时,不要只传递错误对象的两个参数: 例如winston.error(err).

    【讨论】:

      【解决方案2】:

      是的,这是非常糟糕的行为。

      我的解决方法(对于我非常基本的用例)是对消息字符串进行硬编码,因为知道winston 无论如何都会从堆栈中提取并连接消息:

      logger.error("Uncaught async err: ", err);
      

      应该让步

      2020-02-24 12:20:19 - error: "Uncaught async err: The error message."
      

      这不是很好,因为我依靠不良行为来解决它。如果它得到修复,我将不得不调整我的日志记录。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-11
        • 1970-01-01
        • 1970-01-01
        • 2019-11-10
        相关资源
        最近更新 更多