Besides the built-in metrics, you can create custom metrics. For example, you can compute a metric for your business logic, or use the Response.timings object to create a metric for a specific set of endpoints.
Each metric type has a constructor to create a custom metric. The constructor creates a metric object of the declared type. Each type has an add method to take metric measurements.
If you need help constructing a custom metric, read the following sections of this document. They document the procedure and provide examples. If you're comfortable with these already, you might prefer to read the reference documentation for each metric constructor. Each topic has examples to make a custom metric and create thresholds from it.
Custom metrics must be created in init context. This limits memory and ensures that k6 can validate that all thresholds are evaluating defined metrics.
The generic procedure to create a custom metric is as follows:
Import the k6/metrics module. Optionally, specify the type of metrics you want to create with a named import:
In init context, construct a new custom-metric object.
For example, the following creates a custom trend. The object in the script is called myTrend, and its metric appears in the results output as waiting_time.
In the VU iteration code, use the add method to take a measurement.
This VU code makes a request then adds the timing value of the request to the myTrend object.
Custom metrics appear in Results output in both the end-of-test summary and in the granular data points. Each metric type has specific aggregation methods. You can also optionally tag any value for a custom metric. You can use these tags to filter test results.
Here's how the output of the preceding script might look in the end-of-test summary. Since the metric is a trend, k6 calculates various trends based on the number of values and their summation.
Custom metrics are collected from VU threads only at the end of a VU iteration. For long-running scripts, custom metrics might appear only after the test runs a while.
The k6/metrics has examples for defining each type of custom metric, and for defining a threshold on the metric.