Counter
Counter 是一个用于表示自定义累积计数器指标的对象。它是四种自定义指标类型之一。
参数 | 类型 | 描述 |
---|---|---|
name | string | 自定义指标的名称。 |
方法 | 描述 |
---|---|
Counter.add(值, [标签]) | 向计数器指标添加值。 |
阈值中的 Counter 用法
当在阈值表达式中使用 Counter
时,变量必须命名为 count
或 rate
(小写)。例如
count >= 200
// 计数器的值必须大于或等于 200count < 10
// 小于 10。
示例
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);
}