如何使用 Winston/Morgan 记录 JSON HTTP 响应
How to log JSON HTTP Responses using Winston/Morgan
我在 Sails.js 中使用 Winston 和 Morgan 进行所有后端登录,我需要能够记录来自 HTTP get 请求的响应。我需要将它们记录在一个文件中。我的日志文件当前显示所有 http 请求,但不显示响应。我搜索了 Morgan 和 Winston 的所有选项,但找不到 way/option 来执行此操作。我只是想知道你们中是否有人对如何实现这一目标有任何建议?
谢谢!
您可以为 ExpressJS 编写一个中间件函数,在发送响应后记录正文。基于 Node 的 http module 来了解 Connect(以及 Express)如何管理响应主体(这是一个流):您可以挂钩写入该流的两种方法以获取块然后 concat/decode 他们记录下来。简单的解决方案,可以变得更强大,但它表明这个概念是有效的。
function bodyLog(req, res, next) {
var write = res.write;
var end = res.end;
var chunks = [];
res.write = function newWrite(chunk) {
chunks.push(chunk);
write.apply(res, arguments);
};
res.end = function newEnd(chunk) {
if (chunk) { chunks.push(chunk); }
end.apply(res, arguments);
};
res.once('finish', function logIt() {
var body = Buffer.concat(chunks).toString('utf8');
// LOG BODY
});
next();
}
然后在主应用程序路由器中分配任何路由之前设置它:
app.use(bodyLog);
// assign routes
我假设您也可以将其用作 Morgan 中变量的赋值,但我没有研究异步变量赋值的工作原理。
我在 Sails.js 中使用 Winston 和 Morgan 进行所有后端登录,我需要能够记录来自 HTTP get 请求的响应。我需要将它们记录在一个文件中。我的日志文件当前显示所有 http 请求,但不显示响应。我搜索了 Morgan 和 Winston 的所有选项,但找不到 way/option 来执行此操作。我只是想知道你们中是否有人对如何实现这一目标有任何建议? 谢谢!
您可以为 ExpressJS 编写一个中间件函数,在发送响应后记录正文。基于 Node 的 http module 来了解 Connect(以及 Express)如何管理响应主体(这是一个流):您可以挂钩写入该流的两种方法以获取块然后 concat/decode 他们记录下来。简单的解决方案,可以变得更强大,但它表明这个概念是有效的。
function bodyLog(req, res, next) {
var write = res.write;
var end = res.end;
var chunks = [];
res.write = function newWrite(chunk) {
chunks.push(chunk);
write.apply(res, arguments);
};
res.end = function newEnd(chunk) {
if (chunk) { chunks.push(chunk); }
end.apply(res, arguments);
};
res.once('finish', function logIt() {
var body = Buffer.concat(chunks).toString('utf8');
// LOG BODY
});
next();
}
然后在主应用程序路由器中分配任何路由之前设置它:
app.use(bodyLog);
// assign routes
我假设您也可以将其用作 Morgan 中变量的赋值,但我没有研究异步变量赋值的工作原理。