我正在使用node.js和express来处理HTTP请求和响应.通过使用该http.ServerRequest 事件,我可以添加一个钩子并记录HTTP请求.似乎没有类似的事件http.ServerResponse,我想知道如何使用我的服务器发送的一段代码记录所有HTTP响应?
sta*_*er2 10
我创建了一个包含这样的东西的包,出于类似的需要.查看express-request-logger
程序的核心是这样的,它包含一些额外的代码,因此您可以拥有自己的每个请求记录的数据键值映射:
// 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);
};
Run Code Online (Sandbox Code Playgroud)
上面的代码在express中作为中间件运行.看看代码,如果您有其他问题,请在这里或github与我联系.
| 归档时间: |
|
| 查看次数: |
13496 次 |
| 最近记录: |