Documentation for automated readers
A curated documentation index is available at: https://grafana.com/llms.txt
A complete documentation index is available at: https://grafana.com/llms-full.txt
These indexes can help with page discovery before fetching individual documents.
This page is also available in Markdown, which may be easier for automated readers and AI tools to parse than HTML. The Markdown version is available at https://grafana.com/docs/k6/next/javascript-api/k6-metrics/counter.md, or by sending Accept: text/markdown to https://grafana.com/docs/k6/next/javascript-api/k6-metrics/counter/. For broader documentation discovery, the curated index is available at https://grafana.com/llms.txt and the complete index is available at https://grafana.com/llms-full.txt.
This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.
Counter
Counter is an object for representing a custom cumulative counter metric. It’s one of the four metric types.
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the custom metric. |
| Method | Description |
|---|---|
| Counter.add(value, [tags]) | Add a value to the counter metric. |
Counter usage in Thresholds
When Counter is used in a threshold expression, the variable must be called count or rate (lower case).
For example:
count >= 200// value of the counter must be larger or equal to 200count < 10// less than 10.
Examples
import { Counter } from 'k6/metrics';
const myCounter = new Counter('my_counter');
export default function () {
myCounter.add(1);
myCounter.add(2, { tag1: 'myValue', tag2: 'myValue2' });
}import http from 'k6/http';
import { Counter } from 'k6/metrics';
const CounterErrors = new Counter('Errors');
export const options = { thresholds: { Errors: ['count<100'] } };
export default function () {
const res = http.get('https://quickpizza.grafana.com/api/json?name=Bert');
const contentOK = res.json('name') === 'Bert';
CounterErrors.add(!contentOK);
}import { Counter } from 'k6/metrics';
import { sleep } from 'k6';
import http from 'k6/http';
const allErrors = new Counter('error_counter');
export const options = {
vus: 1,
duration: '1m',
thresholds: {
'error_counter': [
'count < 10', // 10 or fewer total errors are tolerated
],
'error_counter{errorType:authError}': [
// Threshold on a sub-metric (tagged values)
'count <= 2', // max 2 authentication errors are tolerated
],
},
};
export default function () {
const auth_resp = http.post('https://quickpizza.grafana.com/api/users/token/login', {
username: 'default',
password: 'supersecure',
});
if (auth_resp.status >= 400) {
allErrors.add(1, { errorType: 'authError' }); // tagged value creates submetric (useful for making thresholds specific)
}
const other_resp = http.get('https://quickpizza.grafana.com/api/json');
if (other_resp.status >= 400) {
allErrors.add(1); // untagged value
}
sleep(1);
}Was this page helpful?
Related resources from Grafana Labs

