使用winston - node js记录一个mongoose db条目

时间:2016-08-11 11:36:03

标签: node.js mongodb mongoose winston

我有一个架构:

var nameSchema = new Schema({
  name: String,
  surname: String,
  word: String
})
var nameSchema = mongoose.model('nameSchema', nameSchema)

每次运行代码时都会更新我的dbs字段。这就是我的dbs条目:

{ "_id" : ObjectId("xxx"), "name" : "Tom", "surname" : "Qwerty", "word" : "secret", "__v" : 0 }

现在,一旦成功保存了这个dbs条目,我也想制作一个winston日志,将这个dbs信息传递给日志。所以它看起来像这样:

 var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.File)({
        filename: './logs/example.log',
        level: 'info',
        timestamp: true,
        event: 'MY DBS ENTRY'   
      })
    ]
  });

我的想法围绕着这条线......

logger.log('info', "db.?? -NOT SURE");

因此日志文件如下所示:

{"level":"info","event":"{"name" : "Tom", "surname" : "Qwerty", "word" : "secret"}","timestamp":"2016-08-11T10:44:49.527Z"}

任何帮助或提示赞赏

1 个答案:

答案 0 :(得分:0)

假设您要插入数据库。保存文档时,您将可以访问当前保存的文档。因此,在回调中,您可以使用该文档创建winston log

var user = new nameSchema();
user.name = "tom";
user.surname = "Qwerty";
user.word = "secret";

user.save(function(err,user)
{
    if(!err)
    {
        //use the currently inserted document and log it in your logger.
        logger.log('info',user);
        // OR:
        // if you just want specific information to log in logger, cerate another variable for it.
        var temp = {};
        temp.name= user.name;
        temp.surname = user.surname;
        temp.word = user.word; 
        logger.log('info',temp);
    }

});