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

200 Views Asked by At

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?

1

There are 1 best solutions below

0
Venkat Cpr On BEST ANSWER

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()
})