No results for

Powered byAlgolia
⚠️ This is archived documentation for v0.34. Go to the latest version

Counter is an object for representing a custom cumulative counter metric. It is one of the four custom metric types.

ParameterTypeDescription
namestringThe name of the custom metric.
MethodDescription
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 200
  • count < 10 // less than 10.

Examples

Simple example
1import { Counter } from 'k6/metrics';
2
3const myCounter = new Counter('my_counter');
4
5export default function () {
6 myCounter.add(1);
7 myCounter.add(2, { tag1: 'myValue', tag2: 'myValue2' });
8}
Simple Threshold usage
1import http from 'k6/http';
2import { Counter } from 'k6/metrics';
3
4const CounterErrors = new Counter('Errors');
5
6export const options = { thresholds: { Errors: ['count<100'] } };
7
8export default function () {
9 const res = http.get('https://test-api.k6.io/public/crocodiles/1/');
10 const contentOK = res.json('name') === 'Bert';
11 CounterErrors.add(!contentOK);
12}
Advanced Thresholds
1import { Counter } from 'k6/metrics';
2import { sleep } from 'k6';
3import http from 'k6/http';
4
5const allErrors = new Counter('error_counter');
6
7export const options = {
8 vus: 1,
9 duration: '1m',
10 thresholds: {
11 'error_counter': [
12 'count < 10', // 10 or fewer total errors are tolerated
13 ],
14 'error_counter{errorType:authError}': [
15 // Threshold on a sub-metric (tagged values)
16 'count <= 2', // max 2 authentication errors are tolerated
17 ],
18 },
19};
20
21export default function () {
22 const auth_resp = http.post('https://test-api.k6.io/auth/token/login/', {
23 username: 'test-user',
24 password: 'supersecure',
25 });
26
27 if (auth_resp.status >= 400) {
28 allErrors.add(1, { errorType: 'authError' }); // tagged value creates submetric (useful for making thresholds specific)
29 }
30
31 const other_resp = http.get('https://test-api.k6.io/public/crocodiles/1/');
32 if (other_resp.status >= 400) {
33 allErrors.add(1); // untagged value
34 }
35
36 sleep(1);
37}