Node.js + Express - How to log the request body and response body - Stack Overflow

PHOTO EMBED

Thu Mar 09 2023 09:04:27 GMT+0000 (Coordinated Universal Time)

Saved by @jaimin #javascript

Hi was looking for same as complete log of request and response as middleware in express js. Found the solution as well w

    /*Added by vikram parihar for log  */
const moment = require('moment');
const rfs = require("rotating-file-stream");
const geoip = require('geoip-lite');
const { PassThrough } = require('stream')
let path = require('path');

const accessLogStream = rfs.createStream('access.log', {
    interval: '1M', // rotate daily
    compress: true,
    path: path.join(__dirname, '../../log')
});

module.exports = function (req, res, next) {
    try {
        let geo = geoip.lookup(req.ip);
        let country = geo ? geo.country : "Unknown";
        let region = geo ? geo.region : "Unknown";
        let log = {
            "time": moment().format('YYYY/MM/DD HH:mm:ss'),
            "host": req.hostname,
            "ip": req.ip,
            "originalUrl": req.originalUrl,
            "geo": {
                "browser": req.headers["user-agent"],
                "Language": req.headers["accept-language"],
                "Country": country,
                "Region": region,
            },
            "method": req.method,
            "path": req.path,
            "url": req.url,
            "body": req.body,
            "params": req.params,
            "query": req.query,
            "response": {
                "body": res.body
            }
        };
        const defaultWrite = res.write.bind(res);
        const defaultEnd = res.end.bind(res);
        const ps = new PassThrough();
        const chunks = [];

        ps.on('data', data => chunks.push(data));

        res.write = (...args) => {
            ps.write(...args);
            defaultWrite(...args);
        }

        res.end = (...args) => {
            ps.end(...args);
            defaultEnd(...args);
        }
        res.on('finish', () => {
            log.response.body = Buffer.concat(chunks).toString()
            accessLogStream.write(JSON.stringify(log) + "\n");
        })
    } catch (error) {
        console.log(error)
        next(error)
    }
    next();
}
content_copyCOPY

https://stackoverflow.com/questions/52310461/node-js-express-how-to-log-the-request-body-and-response-body