Search code examples
node.jswinston

How to use express-winston and winston-mongodb together?


I'm using express-winston and winston-mongodb to log express requests to mongodb.

express-winston config:

expressWinston.logger({
  meta: true,
  //...other unrelated config
})

winston-mongodb config:

new MongoDB({
  //...other unrelated config
})

Logging to mongodb works, but meta field is null. Logging to file/console works perfectly.

The mongo plugin doesn't recognize the express plugin's log format.

How can I get them to play nice?


Solution

  • When you look at the express-winston and winston-mongodb codes, you can easily see the difference. winston-mongodb writes the value that matches the metaKey field to the specified collection. Therefore, if you define it as follows, the meta field will not be null.

    ...
    transports: [
        new winston.transports.Console({
            format: winston.format.json({
                space: 2
            })
        }),
        new winston.transports.MongoDB({
            db: config.db.mongooseURI,
            options: config.db.options,
            collection:'logs',
            capped:true,
            metaKey:'meta'
        }),
    
    
    ],
    meta: true,
    ...