首页 > 解决方案 > 元在 Winston-mongodb 中为空

问题描述

我正在使用 winston-mongodb 模块来记录请求响应。

记录器服务.ts

const options = {
    console: {
        db: DB_URL,
        level: 'info',
        format: format.combine(format.timestamp(), format.json()),
        collection: 'logs',
    },
    error: {
        db: DB_URL,
        level: 'error',
        format: format.combine(format.timestamp(), format.json()),
        collection: 'logs',
    }
  };

const logger = createLogger({
    transports: [
        new MongoDB(options.console),
        new MongoDB(options.error)
    ],
});

服务器.ts

server.listen(port, () => {
    logger.info({message:`Server is up and running on port ${port}`, meta: {
        myProp: 'foo'
      }});
   );

结果:

{
    "_id" : ObjectId("5ed8bd2c726d273004b082ca"),
    "timestamp" : ISODate("2020-06-04T09:21:48.835Z"),
    "level" : "info",
    "message" : "Server is up and running on port 4000 HI",
    **"meta" : null**
}

我正在尝试将元数据添加到记录器。但它在结果中添加了 null 。

标签: node.jsmongodbloggingwinston

解决方案


要获取存储在元中的 err 对象(及其所有 javascript 属性),您需要指定:

format.metadata()    

在 createLogger 调用中。

这是一个工作示例代码:

   // Declare winston
    const winston = require("winston");
    // Import all needed using Object Destructuring
    const { createLogger, format, transports } = require("winston");
    const { combine, timestamp, printf } = format;
    // Export the module
    module.exports = function (err, req, res, next) {
      const logger = createLogger({
        level: "error",
        format: combine(
          format.errors({ stack: true }), // log the full stack
          timestamp(), // get the time stamp part of the full log message
          printf(({ level, message, timestamp, stack }) => {
            // formating the log outcome to show/store
            return `${timestamp} ${level}: ${message} - ${stack}`;
          }),
          format.metadata() // >>>> ADD THIS LINE TO STORE the ERR OBJECT IN META field
        ),
        transports: [
          new transports.Console(), // show the full stack error on the console
          new winston.transports.File({
            // log full stack error on the file
            filename: "logfile.log",
            format: format.combine(
              format.colorize({
                all: false,
              })
            ),
          }),
          new winston.transports.MongoDB({
            db: "mongodb://localhost/logdb",
            // collection: "log",
            level: "error",
            storeHost: true,
            capped: true,
            // metaKey: 'meta'
          }),
        ],
      });
    
      logger.log({
        level: "error",
        message: err,
      });
      // Response sent to client but nothing related to winston
      res.status(500).json(err.message);
    };

推荐阅读