k6 provides many metrics and output formats, but it cannot directly support all possibilities. To store or alter metrics captured during an active k6 test, you can create a custom output extension.
Output extension binaries can use the --out flag to send metrics to a custom place. Some potential reasons for a custom extension could include:
- To support a time-series database not already supported
- To add derived metrics data for storage
- To filter metrics to only the data you care about
Before you start:
To run this tutorial, you'll need the following applications installed:
You also need to install xk6:
Write a simple extension
Set up a directory to work in.
The core of an Output extension is a struct that implements the output.Output interface.
Create a simple example that outputs each set of metrics to the console as received by the AddMetricSamples(samples metrics.SampleContainer) method of the output interface.
Register the module to use these from k6 test scripts.
You must use the registered with the -o, or --out flag when running k6!
The final extension code looks like this:
Notice a couple of things:
The module initializer New() receives an instance of output.Params. With this object, the extension can access the output-specific configuration, interfaces to the filesystem, synchronized stdout and stderr, and more.
AddMetricSamples in this example writes to stdout. This output might have to be buffered and flushed periodically in a real-world scenario to avoid memory leaks. Below we'll discuss some helpers you can use for that.
Compile your extended k6
To build a k6 binary with this extension, run:
xk6-output-logger is the Go module name passed to go mod init
Usually, this would be a URL similar to github.com/grafana/xk6-output-logger.
Use your extension
Now we can use the extension with a test script.
Now, run the test.
The --out logger argument tells k6 to use your custom output. The flag --quiet --no-summary configures k6 to show only custom output.
Your output should look something like this:
Things to keep in mind
- Output structs can optionally implement additional interfaces that allow them to receive thresholds or run-status updates and even interrupt a test.
- Consider using output.SampleBuffer and output.PeriodicFlusher to improve performance given the large amounts of data produced by k6. Refer to statsd output for an example.
- Use the project template as a starting point for your output extension.
Questions? Feel free to join the discussion on extensions in the k6 Community Forum.