首页 > 解决方案 > 无法将日志数据保存到 DB

问题描述

我已经实现了记录器,它成功登录到 .log 文件,但是在尝试将相同的日志保存到 MongoDB 时,它只提供时间戳,而不提供其他日志详细信息。

温斯顿-logger.js:

const winston = require('winston');
require('winston-mongodb');
dateFormat = () => {
   return new Date(Date.now()).toUTCString()
}
class LoggerService {
  constructor(route) {
    // this.log_data = null
    this.route = route
    const logger = winston.createLogger({
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({
          filename: `./logs/${route}.log`
        }),
        new winston.transports.MongoDB({
          db:process.env.MongoDB,
          collection:'log',
        })
      ],
      format: winston.format.json((info) => {
        console.log('infor', info)
        let message = `${JSON.stringify(info.obj)}`
        return message
      })
    });
    this.logger = logger
  }
  async info(message) {
    this.logger.log('info', message);
  }
  async info(message, obj) {
    // this.logger.log('info', message, {
    //   obj
    // })
    this.logger.log('info', obj)
  }
}
module.exports = LoggerService

在 api api.js中调用记录器:

const Logger = require('./config/winston-logger');
const logger = new Logger('app')

app.post('test',(req,res) => {
    something something happens
    logger.info("Request success",{"body":req.body})
}

虽然它保存到日志文件中,但试图保存到 mongo-db 中,但只保存了时间戳。

标签: node.jsexpresswinston

解决方案


我想通了......如果有人面临同样的问题......

//而不是json更改为metaData并将保存在meta中

格式:winston.format.metaData((info) => { console.log('infor', info) let message = ${JSON.stringify(info.obj)} return message })


推荐阅读