如何在Winston中将其他参数添加到自定义日志格式?

时间:2019-01-29 21:22:16

标签: node.js 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类似的行为?

1 个答案:

答案 0 :(得分:0)

您可以对整个内容进行JSON.string化,然后将其放入记录器中,或使用+(执行隐含)代替,(不要这样做)

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

希望这会有所帮助