我使用 Node.js 和 Express 来处理 HTTP 请求和响应。通过使用http.ServerRequest
事件,我可以添加一个挂钩并记录 HTTP 请求。好像没有类似的活动http.ServerResponse
我想知道如何使用我的服务器发送的一段代码来记录所有 HTTP 响应?
出于类似的需求,我创建了一个包来完成这样的事情。查看快速请求记录器
程序的核心是这样的,它包含一些额外的代码,因此您可以拥有自己的按请求记录的数据键值映射:
// Save the real end that we will wrap
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Proxy the real end function
res.end = function(chunk, encoding) {
// Do the work expected
res.end = rEnd;
res.end(chunk, encoding);
// And do the work we want now (logging!)
// Save a few more variables that we can only get at the end
req.kvLog.status = res.statusCode;
req.kvLog.response_time = (new Date() - req._rlStartTime);
// Send the log off to winston
var level = req.kvLog._rlLevel;
delete req.kvLog._rlLevel;
logger.log(level, '', req.kvLog);
};
上面的代码在express中作为中间件运行。查看代码,如果您还有其他问题,请在此处或 github 上与我联系。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)