gpt4 book ai didi

node.js - 添加一个钩子(Hook)以全局记录 node.js/express 中的所有 Node HTTP 响应

转载 作者:IT老高 更新时间:2023-10-28 23:23:52 26 4
gpt4 key购买 nike

我正在使用 node.js 和 express 来处理 HTTP 请求和响应。通过使用 http.ServerRequest 事件,我可以添加一个 Hook 并记录 HTTP 请求。 http.ServerResponse 似乎没有类似的事件,我想知道如何使用我的服务器发送的一段代码记录所有 HTTP 响应?

最佳答案

出于类似的需求,我创建了一个包来做这样的事情。查看 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);
};

以上代码在 express 中作为中间件运行。查看代码,如果您还有其他问题,请在此处或 github 上与我联系。

关于node.js - 添加一个钩子(Hook)以全局记录 node.js/express 中的所有 Node HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8719626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com