Winston 元数据未附加到消息

Winston meta data is not appending to message

为了获得日志为

2021-12-27T20:46:59.136Z -> info: [socketconnection] This message will include a complete object : {name: 'AAA'}

。我创建了一个自定义格式化程序作为 winston config.js

    const { createLogger, format, transports } = require('winston');
const { splat, combine, timestamp, label, printf, simple } = format;
const path = require('path');

const myFormat = printf(({ level, message, timestamp, meta }) => {

  return `${timestamp} -> ${level}:\t${JSON.stringify(message)}`;
});

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${path.join(__dirname, '../logs/app.log')}`,
    handleExceptions: true,
    humanReadableUnhandledException: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    timestamp: true,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: true,
    colorize: true,
  },
};


module.exports = (moduleName) => {
  let logger;
  if (process.env.logging === 'off') {
    logger = createLogger({
      format: combine(
        timestamp(),
        label({ label: `${moduleName}`, message: true }),
        myFormat
      ),
      transports: [
        new winston.transports.File(options.file),
      ],
      exitOnError: false, // do not exit on handled exceptions
    });
  } else {
    logger = createLogger({
      format: combine(
        timestamp(),
        label({ label: `${moduleName}`, message: true }),
        myFormat
      ),
      transports: [
        new transports.File(options.file),
        new transports.Console(options.console),
      ],
      exitOnError: false, // do not exit on handled exceptions
    });
  }

  // create a stream object with a 'write' function that will be used by `morgan`
  logger.stream = {
    write(message) {
      logger.info(message);
    },
  };
  return logger;
};

我是这样的

2021-12-27T21:26:07.148Z -> info: [socketconnection] This message will include a complete object:

记录为,

logger.info('This message will include a complete object:', s);

s 在哪里

`var s = {'name':'AAA'};

Meta 没有附加到消息中。我在这里缺少什么

#1 编辑此行:

const myFormat = printf(({ level, message, timestamp, ...meta }) => {

因为meta是一个数组所以你需要先spread它才能使用它。


#2 winston's 文档说得很清楚:

Properties besides level and message are considered as "meta". i.e.:

所以 meta 没有附加到 message,要使用它试试:

`${JSON.stringify(meta)}`