Appearance
服务器计时中间件
¥Server-Timing Middleware
Server-Timing 中间件在响应标头中提供性能指标。
¥The Server-Timing Middleware provides performance metrics in the response headers.
信息
注意:在 Cloudflare Workers 上,由于 计时器仅显示上次 I/O 的时间,计时器指标可能不准确。
¥Note: On Cloudflare Workers, the timer metrics may not be accurate, since timers only show the time of last I/O.
导入
¥Import
ts
import { Hono } from 'hono'
import { timing, setMetric, startTime, endTime } from 'hono/timing'
import type { TimingVariables } from 'hono/timing'
用法
¥Usage
js
// Specify the variable types to infer the `c.get('metric')`:
type Variables = TimingVariables
const app = new Hono<{ Variables: Variables }>()
// add the middleware to your router
app.use(timing());
app.get('/', async (c) => {
// add custom metrics
setMetric(c, 'region', 'europe-west3')
// add custom metrics with timing, must be in milliseconds
setMetric(c, 'custom', 23.8, 'My custom Metric')
// start a new timer
startTime(c, 'db');
const data = await db.findMany(...);
// end the timer
endTime(c, 'db');
return c.json({ response: data });
});
有条件启用
¥Conditionally enabled
ts
const app = new Hono()
app.use(
'*',
timing({
// c: Context of the request
enabled: (c) => c.req.method === 'POST',
})
)
结果
¥Result
选项
¥Options
<徽章类型="info" 文本="optional" /> 总计:boolean
¥optional total: boolean
显示总响应时间。默认为 true
。
¥Show the total response time. The default is true
.
optional 已启用:boolean
| (c: Context) => boolean
¥optional enabled: boolean
| (c: Context) => boolean
是否应将时间添加到标头中。默认为 true
。
¥Whether timings should be added to the headers or not. The default is true
.
<徽章类型="info" 文本="optional" /> 总描述:boolean
¥optional totalDescription: boolean
总响应时间的描述。默认为 Total Response Time
。
¥Description for the total response time. The default is Total Response Time
.
optional autoEnd:boolean
如果 startTime()
应该在请求结束时自动结束。如果禁用,未手动结束的计时器将不会显示。
¥If startTime()
should end automatically at the end of the request. If disabled, not manually ended timers will not be shown.
optional crossOrigin:boolean
| string
| (c: Context) => boolean | string
此计时标头的来源应可读。
¥The origin this timings header should be readable.
如果为 false,则仅来自当前来源。
¥If false, only from current origin.
如果为真,则来自所有来源。
¥If true, from all origin.
如果是字符串,则来自此域。多个域必须用逗号分隔。
¥If string, from this domain(s). Multiple domains must be separated with a comma.
默认为 false
。查看更多 docs。
¥The default is false
. See more docs.