gpt4 book ai didi

node.js - Fastify 是如何计算响应时间的?

转载 作者:行者123 更新时间:2023-12-02 02:13:16 27 4
gpt4 key购买 nike

上下文:我对请求和响应时间感兴趣。

知道请求何时由 Fastify 管理的第一种方法是添加一个钩子(Hook),如下所示:

fastify.addHook('onRequest', (request, reply, done) => {
request.onRequestTimestamp = Date.now();
done();
});

但信息已经存在:启用 Fastify 日志

fastify = fastify({ logger: true });

我们可以看到例子

{
"level": 30,
"time": 1620659712059,
"pid": 5673,
"hostname": "myhostname",
"reqId": "req-1",
"res": { "statusCode": 200 },
"responseTime": 14.528815001249313,
"msg": "request completed"
}

所以我想 Fastify 本身至少存储了请求何时到达某处 HTTP 服务器的信息,但我找不到位置。

问题:

1- Fastify 如何计算响应时间?

2- Fastify 是否存储(可能在请求对象中)请求时间戳?

最佳答案

您可以通过 reply.getResponseTime() 访问信息方法并在处理程序中添加 onResponse Hook 或跟踪宏步骤

const fastify = require('fastify')({ logger: true })

fastify.get('/', (request, reply) => {
const timeOne = reply.getResponseTime()
setTimeout(() => {
const timeTwo = reply.getResponseTime()
reply.send({
timeOne, timeTwo
})
}, 1000)
})

fastify.listen('8080')

How fastify calculate the responseTime?

它使用私有(private) Symbols 隐藏了 reply 对象中的值

关于node.js - Fastify 是如何计算响应时间的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67473369/

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