添加钩子以全局记录node.js/express中的所有节点HTTP响应

Edm*_*der 9 node.js express

我正在使用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与我联系.


Dar*_*añé 10

只要在node.js 0.8.12之后在end()函数上发出了finish事件,就不再需要monkeypatch.

事实上,它最初发布为年底0.8.8(还要检查这个),但它打破了可写流复式,所以更名完成.

  • 我检查了Node 0.8.14和0.8.23并且发出了`end`,而不是`finish`.您链接的提交包含在0.9/0.10分支中(自几周前以来,GH在提交消息下方显示). (2认同)