0Pricing
Load Testing & Performance Benchmarking (JMeter & k6) · Aula

Métricas personalizadas e tendências no k6

Defina suas próprias métricas Counter, Gauge, Rate e Trend no k6 para medir exatamente o que importa em seus cenários avançados.

Métricas personalizadas e tendências no k6 é uma aula grátis de Load Testing & Performance Benchmarking (JMeter & k6) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Load Testing & Performance Benchmarking (JMeter & k6), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Load Testing & Performance Benchmarking (JMeter & k6) inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.js

Choosing 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.

  • Counter sums, Gauge keeps the last value, Rate tracks ratios, Trend reports stats.
  • Add tags and thresholds to custom metrics for targeted SLOs.
  • They appear in the summary and any output backend.

Perguntas Frequentes

A aula “Métricas personalizadas e tendências no k6” é grátis?

Sim — o texto completo de “Métricas personalizadas e tendências no k6” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Load Testing & Performance Benchmarking (JMeter & k6), atualize para CoddyKit PRO. O curso de Load Testing & Performance Benchmarking (JMeter & k6) inclui 4 aulas no total.

O que vou aprender em “Métricas personalizadas e tendências no k6”?

Defina suas próprias métricas Counter, Gauge, Rate e Trend no k6 para medir exatamente o que importa em seus cenários avançados. Você pratica Load Testing & Performance Benchmarking (JMeter & k6) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Load Testing & Performance Benchmarking (JMeter & k6)?

Nenhuma experiência prévia é necessária. Load Testing & Performance Benchmarking (JMeter & k6) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Métricas personalizadas e tendências no k6”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Load Testing & Performance Benchmarking (JMeter & k6)?

Sim. Cada aula de Load Testing & Performance Benchmarking (JMeter & k6) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Cenários de Usuários Virtuais (VUs)
  2. Parametrização de Dados no k6
  3. Execução do k6 na Nuvem
  4. Métricas personalizadas e tendências no k6
← Voltar para Load Testing & Performance Benchmarking (JMeter & k6)