我想在我的日志文件中记录响应正文
我已经尝试了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" })发布于 2019-07-25 11:36:04
覆盖res.send / res.json方法,customize :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(...))发布于 2020-07-16 14:03:57
你可以使用这个
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)发布于 2021-10-13 14:06:50
使用node v16和摩根自定义日志格式更新上述答案
middleware.ts
export const setResponseBody = (req: any, res: any, next: any) => {
const oldWrite = res.write,
oldEnd = res.end,
chunks: any = [];
res.write = function (chunk: any) {
chunks.push(Buffer.from(chunk));
oldWrite.apply(res, arguments);
};
res.end = function (chunk: any) {
if (chunk) {
chunks.push(Buffer.from(chunk));
}
const body = Buffer.concat(chunks).toString('utf8');
res.__custombody__ = body;
oldEnd.apply(res, arguments);
};
next();
};app.ts
morgan.token('responseBody', function (req, res: any) {
if (res['statusCode'] != 200) {
return res['__custombody__'] || null;
}
return null;
});
const app = express();
app.use(morgan('responseBody=:responseBody'));https://stackoverflow.com/questions/57191236
复制相似问题