我要将响应正文记录在我的日志文件中
我尝试了morgan-body,但我想将响应记录在文件中而不是控制台中
以下代码将记录请求正文,因此也有方法记录响应吗?
morgan.token('body', function (req, res) { return JSON.stringify(req.body) });
app.use(morgan(':method :url :status :response-time ms - :res[content-length] :body - :req[content-length]', {
stream: logger.successLogStream,
skip: function (req, res) { return res.statusCode >= 400 }
}));
app.use(morgan(':method :url :status :response-time ms - :res[content-length] :body - :req[content-length]', {
stream: logger.errorLogStream,
skip: function (req, res) { return res.statusCode < 400 }
}));
例如,我要记录以下错误消息
return res.status(400).send({ "message": "Campaign id is not defined" })
答案 0 :(得分:0)
重写res.send / res.json方法,自定义:res-body并注意在路径后放置摩根
morgan.token('resBody', (req, res) => res.resBody);
res.send = (...args) => {
res.oldsend(...args);
res.resBody = JSON.stringify(args);
};
app.use(routes)
app.use(morgan(...))
答案 1 :(得分:0)
您可以使用此
const app = express()
const originalSend = app.response.send
app.response.send = function sendOverWrite(body) {
originalSend.call(this, body)
this.__custombody__ = body
}
morgan.token('res-body', (_req, res) =>
JSON.stringify(res.__custombody__),
)
...
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan(loggerFormat, { stream: logStream }))
app.use(...routers)