mongodbexpresswinstonmorgan

Log all API request to mongoDB using morgan and winston with node express


I want to log all request to MongoDB. Each document should have the HTTP method, the person who made the request, the _id of the document that was Update/Inserted/Retrieved and time the request was made. Can someone please assist?


Solution

  • I suggest using the package express-winston. See link for documentation. After install package, npm i express-winston, create middleware name logger.js (or whatever you please). copy the following code below

    const expressWinston = require('express-winston');
    
    const requestLog = expressWinston.logger({
      transports: [
        new winston.transports.Console({
          format: winston.format.json({
            space: 2
          })
        }),
        new winston.transports.MongoDB({
          db: 'localhost:27001', //Your Db connection
          options: {
            useNewUrlParser: true,
            poolSize: 2,
            autoReconnect: true
          }
        })
      ],
      meta: true,
      msg: "Request: HTTP {{req.method}} {{req.url}}; Username: {{req.user.preferred_username}}; ipAddress {{req.connection.remoteAddress}}",
      requestWhitelist: [
        "url",
        "method",
        "httpVersion",
        "originalUrl",
        "query",
        "body"
      ]
    });
    
    exports.requestLog = requestLog;

    The in your app.js file, require the logger file so that is applied globally:

    const logger = require('../middleware/logger');
    const express = require('express');
    const app = express();
    
    app.use(logger.requestLog);

    There are additional options you can include like for example: expressWinston.responseWhitelist.push('body')

    that will provide the response body in the object.

    You can remove the transport for the console if you don't want to see all request, i only added it so you can see the object without going to the database each time.