node.jsexpressmorgan

is there is any way to log the response body in nodejs


I'm trying to create a logger for my own system. I have a problem getting the res.body, i am using morgan as a middleware and wrote cutome tokens for getting req and res body, i can easily get the request body but not response body.

  morgan.token('qbody', (req) => {
    return JSON.stringify(req.body)
})

morgan.token('sbody', (res) => {

    return JSON.stringify(res.body)
})

is there is any way to get the response body?


Solution

  • by using method overloading i sloved this problem

    app.use(function (req, res, next) {
    var json = res.json
    res.json = function (obj) {
        function loging(obj) {
            console.log(obj) //res.body
            console.log(req.body)
        }
        loging(obj)
    
        json.call(this, obj)
    }
    next()
    })