k6 中的自定义指标与趋势
在 k6 中定义自己的计数器、仪表、比率和趋势指标,准确衡量高级场景中真正重要的内容。
k6 中的自定义指标与趋势 是 CoddyKit 上的免费 Load Testing & Performance Benchmarking (JMeter & k6) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Load Testing & Performance Benchmarking (JMeter & k6) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Load Testing & Performance Benchmarking (JMeter & k6) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Beyond Built-in Metrics
k6 ships with built-in metrics like http_req_duration, but advanced tests often need to measure domain-specific values: items in a cart, business transaction time, or a custom error rate. k6 lets you create custom metrics.
The Four Metric Types
k6 offers four custom metric types from k6/metrics:
- Counter — cumulative sum.
- Gauge — last recorded value.
- Rate — percentage of non-zero/true values.
- Trend — statistics like min, max, avg, p95.
Importing Metric Constructors
Import the constructors you need and create the metric objects in module scope so they are shared across iterations.
import { Counter, Trend, Rate, Gauge } from 'k6/metrics';A Counter Example
A Counter accumulates a value over the whole test. Here we count how many orders were created.
const ordersCreated = new Counter('orders_created');
export default function () {
ordersCreated.add(1);
}A Trend for Timing
A Trend collects a series of numbers and reports statistics. It is ideal for timing custom logic.
import http from 'k6/http';
const loginTime = new Trend('login_time');
export default function () {
const res = http.post('https://test.k6.io/login');
loginTime.add(res.timings.duration);
}A Rate for Success Ratio
A Rate tracks how often a condition is true. Add true or false and k6 reports the percentage of trues.
const successRate = new Rate('success_rate');
successRate.add(res.status === 200);A Gauge for Last Value
A Gauge keeps only the most recent value you add. Use it for things like the current queue length reported by an endpoint.
const queueDepth = new Gauge('queue_depth');
queueDepth.add(42);Tagging Custom Metrics
Just like built-in metrics, you can attach tags when adding a value. This lets you slice your custom metric by endpoint or feature.
loginTime.add(res.timings.duration, { region: 'eu' });Thresholds on Custom Metrics
Custom metrics integrate fully with thresholds. You can fail a run if your business metric crosses a limit.
export const options = {
thresholds: {
login_time: ['p(95)<500'],
success_rate: ['rate>0.98'],
},
};Reading Custom Metrics in Summary
At the end of a run, custom metrics appear in the end-of-test summary alongside built-in ones, showing the appropriate statistics for their type.
k6 run scenario.jsChoosing the Right Type
Picking the correct metric type matters: use a Trend for durations, a Rate for success ratios, a Counter for totals, and a Gauge for snapshot values. The wrong type gives misleading summaries.
Quick Check
Pick the right metric type for the job.
Recap
You can now extend k6 with custom metrics.
Countersums,Gaugekeeps the last value,Ratetracks ratios,Trendreports stats.- Add tags and thresholds to custom metrics for targeted SLOs.
- They appear in the summary and any output backend.
常见问题解答
「k6 中的自定义指标与趋势」课时是免费的吗?
是的 — 「k6 中的自定义指标与趋势」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Load Testing & Performance Benchmarking (JMeter & k6) 课程的其余内容,请升级到 CoddyKit PRO。 Load Testing & Performance Benchmarking (JMeter & k6) 课程共包含 4 节课。
「k6 中的自定义指标与趋势」这节课中我会学到什么?
在 k6 中定义自己的计数器、仪表、比率和趋势指标,准确衡量高级场景中真正重要的内容。 你通过在浏览器中直接运行的动手代码来练习 Load Testing & Performance Benchmarking (JMeter & k6),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Load Testing & Performance Benchmarking (JMeter & k6) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Load Testing & Performance Benchmarking (JMeter & k6) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「k6 中的自定义指标与趋势」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Load Testing & Performance Benchmarking (JMeter & k6) 课中编写并运行代码吗?
能。每节 Load Testing & Performance Benchmarking (JMeter & k6) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 虚拟用户场景(VUs)
- k6 中的数据参数化
- 使用 k6 在云端执行
- k6 中的自定义指标与趋势