The k6/metrics module provides classes for creating custom metrics.
Metric Types
Counter
A metric that cumulatively sums added values.
import { Counter } from 'k6/metrics';
const myCounter = new Counter('my_counter');
export default function () {
myCounter.add(1);
}
Metric name (must be unique)
Whether the metric represents time values
Adds a value to the counter.
Custom tags for this data point
Gauge
A metric that stores the latest value added to it.
import { Gauge } from 'k6/metrics';
const myGauge = new Gauge('my_gauge');
export default function () {
myGauge.add(42);
}
Metric name (must be unique)
Whether the metric represents time values
Sets the gauge to the specified value.
Rate
A metric that tracks the percentage of added values that are non-zero.
import { Rate } from 'k6/metrics';
const myRate = new Rate('my_rate');
export default function () {
myRate.add(true); // or 1
myRate.add(false); // or 0
}
Metric name (must be unique)
Whether the metric represents time values
Adds a boolean or numeric value to the rate.
Trend
A metric that calculates statistics (min, max, avg, percentiles) on added values.
import { Trend } from 'k6/metrics';
const myTrend = new Trend('my_trend');
export default function () {
myTrend.add(100);
myTrend.add(200);
}
Metric name (must be unique)
Whether the metric represents time values (enables time-based formatting)
Adds a value to the trend.
Complete Example
import http from 'k6/http';
import { Counter, Gauge, Rate, Trend } from 'k6/metrics';
import { check } from 'k6';
let myCounter = new Counter('my_counter');
let myGauge = new Gauge('my_gauge');
let myRate = new Rate('my_rate');
let myTrend = new Trend('my_trend');
let maxResponseTime = 0.0;
export default function () {
let res = http.get('http://httpbin.org/');
let passed = check(res, { 'status is 200': (r) => r.status === 200 });
// Add one for number of requests
myCounter.add(1);
// Set max response time seen
maxResponseTime = Math.max(maxResponseTime, res.timings.duration);
myGauge.add(maxResponseTime);
// Add check success or failure
myRate.add(passed);
// Track response time
myTrend.add(res.timings.duration);
}
Usage Notes
Custom metrics must be declared in the init context (outside the default function). Adding values to metrics can only be done in the VU context.
// ✅ Correct - declare in init context
import { Counter } from 'k6/metrics';
const myCounter = new Counter('my_counter');
export default function () {
// ✅ Correct - add values in VU context
myCounter.add(1);
}
You can attach custom tags to individual metric data points:
import { Counter } from 'k6/metrics';
const myCounter = new Counter('api_requests');
export default function () {
myCounter.add(1, { endpoint: '/users', method: 'GET' });
myCounter.add(1, { endpoint: '/posts', method: 'POST' });
}