0Pricing
Load Testing & Performance Benchmarking (JMeter & k6) · Lección

Métricas personalizadas y tendencias en k6

Defina sus propias métricas Counter, Gauge, Rate y Trend en k6 para medir exactamente lo que importa en sus escenarios avanzados.

Métricas personalizadas y tendencias en k6 es una lección gratuita de Load Testing & Performance Benchmarking (JMeter & k6) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Load Testing & Performance Benchmarking (JMeter & k6), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Load Testing & Performance Benchmarking (JMeter & k6) incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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.

Preguntas frecuentes

¿La lección «Métricas personalizadas y tendencias en k6» es gratis?

Sí — el texto completo de «Métricas personalizadas y tendencias en k6» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Load Testing & Performance Benchmarking (JMeter & k6), actualiza a CoddyKit PRO. El curso de Load Testing & Performance Benchmarking (JMeter & k6) incluye 4 lecciones en total.

¿Qué aprenderé en «Métricas personalizadas y tendencias en k6»?

Defina sus propias métricas Counter, Gauge, Rate y Trend en k6 para medir exactamente lo que importa en sus escenarios avanzados. Practicas Load Testing & Performance Benchmarking (JMeter & k6) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Load Testing & Performance Benchmarking (JMeter & k6)?

No se requiere experiencia previa. Load Testing & Performance Benchmarking (JMeter & k6) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Métricas personalizadas y tendencias en k6»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Load Testing & Performance Benchmarking (JMeter & k6)?

Sí. Cada lección de Load Testing & Performance Benchmarking (JMeter & k6) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Escenarios de usuarios virtuales (VUs)
  2. Parametrización de datos en k6
  3. Ejecución de k6 en la nube
  4. Métricas personalizadas y tendencias en k6
← Volver a Load Testing & Performance Benchmarking (JMeter & k6)