首页 > 解决方案 > 如何在 Winston 中为自定义日志格式添加额外参数?

问题描述

当您 console.log 时,您可以添加额外的参数:

console.log("The message", { foo: 123 });

这将打印消息以及第二个参数(和任何其他参数)的序列化版本。我使用 Winston 创建自定义日志格式,如下所示:

const winston = require('winston');

const logFormat = winston.format.printf(({ level, message, timestamp }) => {
    return `${timestamp} ${level}: ${message}`;
  });

  const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(winston.format.timestamp(), logFormat),
    transports: [
      new winston.transports.File({ filename: './logs/error.log', level: 'error' }),
      new winston.transports.File({ filename: './logs/combined.log' })
    ]
  });

这将在执行时忽略任何额外的参数logger.info("This gets in the logs", { this: "not" });

如何使用 Winston 实现与 console.log 类似的行为?

标签: node.jswinston

解决方案


您可以 JSON.stringify 整个事情并将其放入记录器或使用 + (执行连接)而不是 a , (不这样做)

logger.info("This gets in the logs"+ JSON.stringify({ this: "not" }));

希望这可以帮助


推荐阅读