API Reference
Entry point for initializing telemetry in a Locust test run.
- locust_telemetry.entrypoint.initialize(*args, **kwargs)[source]
Register all the available plugins and start the coordinator.
For autodiscovery use only. Manual users should call setup_telemetry().
- Return type:
None
- locust_telemetry.entrypoint.setup_telemetry()[source]
High-level convenience initializer.
Since Locust doesn’t have auto-discovery for plugins yet, this explicitly configures CLI args and initializes telemetry.
- Return type:
None
This module provides structured JSON logging for Locust Telemetry.
Features - Outputs logs in JSON format compatible with RFC3339 timestamps. - Custom formatter for millisecond-precision timestamps in UTC. - Configures loggers specifically for the locust_telemetry namespace. - Provides a convenience function to apply the logging configuration.
- class locust_telemetry.logger.RFC3339JsonFormatter(*args, json_default=None, json_encoder=None, json_serializer=<function dumps>, json_indent=None, json_ensure_ascii=True, **kwargs)[source]
Bases:
JsonFormatterCustom JSON formatter for RFC3339 timestamps.
This formatter ensures timestamps are: - in ISO 8601 / RFC3339 format - millisecond-precision - in UTC (Z suffix)
- Parameters:
args – see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter]
json_default (Optional[Callable]) – a function for encoding non-standard objects
json_encoder (Optional[Callable]) – custom JSON encoder
json_serializer (Callable) – a [json.dumps](https://docs.python.org/3/library/json.html#json.dumps)-compatible callable that will be used to serialize the log record.
json_indent (Optional[Union[int, str]]) – indent parameter for the json_serializer
json_ensure_ascii (bool) – ensure_ascii parameter for the json_serializer
kwargs – see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter]
- formatTime(record, datefmt=None)[source]
Format the log record timestamp in RFC3339 with milliseconds.
- Parameters:
record (logging.LogRecord) – Log record to format
datefmt (Optional[str]) – Ignored; kept for compatibility
- Returns:
ISO 8601 formatted timestamp
- Return type:
- locust_telemetry.logger.configure_logging(level='INFO')[source]
Apply the logging configuration to the Python logging system.
- Parameters:
level (str) – Log level for the telemetry logger (e.g. “DEBUG”, “INFO”, “WARNING”).
This module provides helper functions for managing test metadata in a Locust Telemetry setup. Metadata is generated on the master node, propagated to worker nodes, and attached to the Locust environment.
- locust_telemetry.metadata.set_test_metadata(environment, metadata)[source]
This function attaches the given metadata to the environment (environment.telemetry_meta). Metadata should be a dictionary where the values can either callable or static value.
- Parameters:
environment (Environment) – The Locust environment instance.
metadata (Dict) – Dict items will be set as metadata (environment.telemetry_meta)
- Return type:
None
- class locust_telemetry.common.helpers.InstrumentSpec(metric, unit, factory, callbacks=None)[source]
Bases:
objectSpecification for creating an OpenTelemetry metric instrument.
- Parameters:
metric (TelemetryEventsEnum | TelemetryMetricsEnum)
unit (str)
factory (Callable)
callbacks (Optional[List[Callable]])
- metric: TelemetryEventsEnum | TelemetryMetricsEnum
- factory: Callable
- locust_telemetry.common.helpers.warmup_psutil(process)[source]
Initialize psutil process metrics to ensure accurate first readings.
Many psutil methods, such as cpu_percent(), require a prior call to establish a baseline before returning meaningful values. This function calls the necessary methods to “warm up” the process metrics.
- Parameters:
process (psutil.Process) – The process object for which to initialize CPU and memory statistics.
- Return type:
None
- locust_telemetry.common.helpers.convert_bytes_to_mib(value)[source]
Convert a value from bytes to mebibytes (MiB).
- locust_telemetry.common.helpers.get_utc_time_with_buffer(seconds_buffer)[source]
Compute a UTC timestamp string with a buffer added, formatted in ISO 8601.
- locust_telemetry.common.helpers.add_percentiles(stats)[source]
Add friendly percentile keys to a Locust stats dictionary.
Converts Locust percentile keys to simpler names: - “response_time_percentile_0.95” -> “percentile_95” - “response_time_percentile_0.99” -> “percentile_99”
Caution: This mutates the original dict. copy is intentionally not used because it’s not necessary
- locust_telemetry.common.helpers.create_otel_histogram(meter, name, description, unit='ms', **kwargs)[source]
Create an OpenTelemetry histogram for recording distributions of values.
- locust_telemetry.common.helpers.create_otel_observable_gauge(meter, name, description, unit='1', callbacks=None, **kwargs)[source]
Create an OpenTelemetry Observable Gauge.
Observable gauges capture instantaneous values, which are updated via callback functions.
- Parameters:
meter (Meter) – OpenTelemetry Meter used to create the gauge.
name (str) – Name of the metric.
description (str) – Human-readable description of the metric.
unit (str, optional) – Unit of measurement (default is dimensionless “1”).
callbacks (list[Callable], optional) – List of callback functions to provide gauge values.
- Returns:
Configured Observable Gauge instrument.
- Return type:
Any
- locust_telemetry.common.helpers.create_otel_counter(meter, name, description, unit='1', **kwargs)[source]
Create an OpenTelemetry Counter instrument.
A Counter is a cumulative metric that can only increase. Suitable for counting events (e.g., test start/stop events).
- Parameters:
- Returns:
Configured Counter instrument.
- Return type:
Counter
- locust_telemetry.common.helpers.get_source_id(env)[source]
Get source if of the current runner. If its master then it returns as ‘master’ and for workers - it will return as ‘worker-<index>’
- Parameters:
env (Environment) – Locust environment
- Returns:
If its master then it returns as ‘master’ and for workers - it will return as ‘worker-<index>’
- Return type:
Telemetry CLI integration for Locust.
- locust_telemetry.core.cli.register_telemetry_cli_args(parser)[source]
Register core telemetry CLI arguments for Locust.
This function creates (or reuses) a dedicated argument group for telemetry-related options. It ensures that
--testplanand--enable-telemetry-recorderare available.- Parameters:
parser (LocustArgumentParser) – The Locust argument parser instance.
- Returns:
The argument group created for telemetry options, or the existing one if already registered.
- Return type:
_ArgumentGroup
Singleton coordinator responsible for coordinating telemetry lifecycle with Locust.
- class locust_telemetry.core.coordinator.TelemetryCoordinator(*args, **kwargs)[source]
Singleton responsible for coordinating telemetry lifecycle with Locust.
Responsibilities
Setup and propagate test metadata between master and workers.
Register worker message handlers to receive metadata from master.
Load telemetry recorders via
RecorderPluginManager.Ensure singleton initialization (one coordinator per process).
Initialize the coordinator with a recorder manager.
- param recorder_plugin_manager:
Manager responsible for registering and loading telemetry recorders.
- type recorder_plugin_manager:
RecorderPluginManager
- __init__(recorder_plugin_manager)[source]
Initialize the coordinator with a recorder manager.
- Parameters:
recorder_plugin_manager (RecorderPluginManager) – Manager responsible for registering and loading telemetry recorders.
- initialize()[source]
Register lifecycle hooks into Locust events.
Steps
Register worker metadata handlers.
Load registered recorders on Locust init.
Setup metadata propagation at test start.
Cleanup metadata at test stop (future extension).
Notes
Safe to call multiple times; only registers hooks once.
- Return type:
None
- class locust_telemetry.core.events.TelemetryEventsEnum(*values)[source]
- TEST = 'locust.tl.event.test.events'
- TEST_START = 'locust.tl.event.test.start'
- TEST_STOP = 'locust.tl.event.test.stop'
- SPAWNING_COMPLETE = 'locust.tl.event.spawn.complete'
- CPU_WARNING = 'locust.tl.event.cpu.warning'
- class locust_telemetry.core.events.TelemetryMetricsEnum(*values)[source]
- CPU = 'locust.tl.system.metric.cpu'
- MEMORY = 'locust.tl.system.metric.mem'
- NETWORK = 'locust.tl.system.metric.network'
- REQUEST_STATS = 'locust.tl.request.metric.stats'
- REQUEST_SUCCESS = 'locust.tl.request.metric.success'
- REQUEST_ERROR = 'locust.tl.request.metric.error'
- USER = 'locust.tl.user.metric.count'
Core handler abstractions for Locust Telemetry integration.
This module defines abstract base classes (ABCs) that serve as contracts for handling Locust events and recording telemetry. These abstractions separate event handling (e.g., test lifecycle, requests, system metrics) from the concrete output mechanism (e.g., JSON logs, OpenTelemetry exporters).
Design Notes
- These base classes should live under locust_telemetry/core as they
define the foundational contracts of the telemetry framework.
- Shared helpers (e.g., metric collectors, enums) belong in
locust_telemetry/common.
- class locust_telemetry.core.handlers.BaseOutputHandler(env)[source]
Abstract base class for telemetry output handlers.
Implementations define how telemetry events and metrics are emitted, such as: - Writing structured JSON logs - Exporting OpenTelemetry signals - Integrating with custom monitoring backends
Each handler receives the Locust
Environmentfor context.Responsibilities
Serialize and dispatch telemetry events.
Record metrics with associated attributes.
Provide run-level context (e.g., run_id, testplan, source).
- Parameters:
env (Environment)
- class locust_telemetry.core.handlers.BaseLifecycleHandler(output, env)[source]
Abstract base class for handling Locust test lifecycle events.
Responds to key lifecycle transitions such as
test_start,test_stop,spawning_complete, andcpu_warning. Implementations typically forward these events to a telemetry output handler.Responsibilities
Translate Locust lifecycle events into telemetry signals.
Invoke
OutputHandlerBase.record_eventwith appropriate metadata.
- Parameters:
output (BaseOutputHandler)
env (Environment)
- class locust_telemetry.core.handlers.BaseRequestHandler(output, env)[source]
Abstract base class for handling Locust request events.
Transforms request/response events into telemetry signals, such as request durations, status codes, or error rates.
Responsibilities
Handle request events emitted by Locust.
Forward request metadata to the telemetry output handler.
- abstractmethod start()[source]
Start requests metrics collection (push loop or callback registration).
- Return type:
None
- Parameters:
output (BaseOutputHandler)
env (Environment)
- class locust_telemetry.core.handlers.BaseSystemMetricsHandler(output, env)[source]
Abstract base class for system metrics collection.
Controls the lifecycle of metrics recording. Implementations may: - Start a background loop to periodically push metrics (e.g., JSON logging). - Register pull-based callbacks (e.g., OpenTelemetry observables).
Responsibilities
Manage start/stop of system metrics collection.
Emit system-level metrics (e.g., CPU, memory, network).
- Parameters:
output (BaseOutputHandler)
env (Environment)
Recorder manager for Locust Telemetry.
- class locust_telemetry.core.manager.RecorderPluginManager(*args, **kwargs)[source]
Singleton class that manages telemetry recorder plugin registration and loading.
Responsibilities
Register recorder plugins provided by extensions.
Maintain a central recorder plugin registry per process.
Safely load recorder plugins when requested by the orchestrator.
Initialize the plugin manager.
Ensures that the plugin registry is created only once for the process. Subsequent instantiations will reuse the existing singleton instance.
- __init__()[source]
Initialize the plugin manager.
Ensures that the plugin registry is created only once for the process. Subsequent instantiations will reuse the existing singleton instance.
- property recorder_plugins: List[BaseRecorderPlugin]
Get the list of registered recorder plugins.
- Returns:
The currently registered recorder plugin instances.
- Return type:
List[BaseRecorderPlugin]
- register_recorder_plugin(plugin)[source]
Register a telemetry recorder plugin for later loading.
A plugin will only be added once to prevent duplicate registration.
- Parameters:
plugin (BaseRecorderPlugin) – The recorder plugin instance to register.
- Return type:
None
- register_plugin_clis(group)[source]
Register CLI arguments for all recorder plugins.
This method is typically invoked by
TelemetryOrchestratorduring Locust’sinit_command_line_parserphase. Each recorder plugin receives the locust-telemetry CLI argument group.- Parameters:
group (argparse._ArgumentGroup) – The Locust CLI argument group.
- Return type:
None
- register_plugin_metadata(environment)[source]
Collect and register test metadata from all recorder plugins.
This method aggregates metadata contributed by each registered recorder plugin, merges it into the default environment metadata, and sets it on the given Locust environment.
- Parameters:
environment (Environment) – The Locust environment instance where the metadata will be stored.
- Returns:
A dictionary containing the merged environment metadata, including contributions from all recorder plugins.
- Return type:
Dict
- load_recorder_plugins(environment, **kwargs)[source]
Load and activate all registered recorder plugins.
This method is typically invoked by
TelemetryOrchestratorduring Locust’sinitphase. Each recorder plugin receives the current environment and any additional context provided by the event system.- Parameters:
environment (Environment) – The Locust environment instance.
**kwargs (Any) – Additional context passed by the event system.
- Raises:
Exception – Logs and propagates plugin load failures with context.
- Return type:
None
Base interface for Telemetry Recorder plugins in Locust.
- class locust_telemetry.core.plugin.BaseRecorderPlugin[source]
Abstract base class for all telemetry recorder plugins.
Extend this class to implement custom telemetry features such as metrics reporting, external integrations, or event capture.
Each recorder plugin can: - Define optional CLI arguments for runtime configuration. - Register master-side recorders (for aggregation, central logging, etc.). - Register worker-side recorders (for local metric capture).
- abstractmethod add_test_metadata()[source]
Add any metadata required by the plugin to both master and worker environment. Metadata that is returned from this method can be accessed from environment.telemetry_meta
- Return type:
- abstractmethod add_cli_arguments(group)[source]
Register recorder plugin-specific CLI arguments or environment variables.
Override in your plugin if runtime configuration is required.
- Parameters:
group (_ArgumentGroup) – The argument parser group to which options can be added.
- Return type:
None
- abstractmethod load_master_recorders(environment, **kwargs)[source]
Register telemetry recorders that should run on the master process.
Override this method in your recorder plugin to implement master-side behavior.
- Parameters:
environment (Environment) – The Locust environment instance.
**kwargs (Any) – Additional context passed by the coordinator or event system.
- Return type:
None
- abstractmethod load_worker_recorders(environment, **kwargs)[source]
Register telemetry recorders that should run on each worker process.
Override this method in your recorder plugin to implement worker-side behavior.
- Parameters:
environment (Environment) – The Locust environment instance.
**kwargs (Any) – Additional context passed by the coordinator or event system.
- Return type:
None
- load(environment, **kwargs)[source]
Entry point for recorder plugin initialization.
Automatically invoked by
RecorderPluginManagerduring Locust’s init phase. Dispatches to the correct recorder registration method depending on runner type.- Parameters:
environment (Environment) – The Locust environment instance.
**kwargs (Any) – Additional context passed by the coordinator or event system.
- Return type:
None
- class locust_telemetry.core.recorder.BaseRecorder(env, output_handler_cls, lifecycle_handler_cls, system_handler_cls, requests_handler_cls)[source]
Abstract base class for telemetry recorders.
Responsibilities
Store the Locust environment and telemetry handlers.
Provide helper methods for concrete recorders.
Allow subclasses to register event listeners as needed.
- on_cpu_warning(*args, **kwargs)[source]
Handle a CPU usage warning raised by Locust.
Forwards the warning to the lifecycle handler with telemetry metadata.
- Parameters:
*args (Any) – args from locust event
**kwargs (Any) – Additional keyword arguments from the Locust event.
- Return type:
None
- Parameters:
env (Environment)
output_handler_cls (Type[BaseOutputHandler])
lifecycle_handler_cls (Type[BaseLifecycleHandler])
system_handler_cls (Type[BaseSystemMetricsHandler])
requests_handler_cls (Type[BaseRequestHandler])
- class locust_telemetry.core.recorder.MasterNodeRecorder(*args, **kwargs)[source]
Telemetry recorder for the Locust master node.
Registers master-specific event listeners and coordinates telemetry collection across system, lifecycle, and request metrics.
- on_test_start(*args, **kwargs)[source]
Handle the test_start event.
Starts lifecycle recording, request metrics collection, and system metrics collection.
- class locust_telemetry.core.recorder.WorkerNodeRecorder(*args, **kwargs)[source]
Telemetry recorder for the Locust worker node.
Focuses on system metrics and CPU warnings, delegating lifecycle event logging to the master.
JSON telemetry handlers for Locust. This module provides handler implementations for lifecycle events, system metrics, request metrics, and structured JSON output. These handlers are used by the JSON telemetry recorders for both master and worker nodes.
- class locust_telemetry.recorders.json.handlers.JsonTelemetryOutputHandler(env)[source]
Bases:
BaseOutputHandlerOutput handler for JSON-based telemetry logging.
Responsibilities
Log lifecycle events and system/request metrics in JSON format.
Enrich logs with run-level context including run ID, testplan, and source (master/worker).
- Parameters:
env (Environment)
- class locust_telemetry.recorders.json.handlers.JsonTelemetryLifecycleHandler(output, env)[source]
Bases:
BaseLifecycleHandlerLifecycle handler for JSON telemetry.
This class inherits from LifecycleHandlerBase and handles Locust test lifecycle events. For JSON telemetry, lifecycle events are forwarded to the output handler for structured logging.
Custom behavior: On test stop, adjusts the stop timestamp to account for a buffer used in JSON graphs, and emits a SPAWNING_COMPLETE event.
- Parameters:
output (BaseOutputHandler)
env (Environment)
- output
Output handler responsible for recording telemetry events.
- Type:
OutputHandlerBase
- env
The Locust environment instance.
- Type:
Environment
- on_test_stop(*args, **kwargs)[source]
Handle the test_stop event for JSON telemetry.
Adjusts the test stop time by TEST_STOP_BUFFER_FOR_GRAPHS seconds to allow for post-test graph updates, then forwards the event to the output handler.
- Parameters:
*args (Any) – Positional arguments passed by Locust.
**kwargs (Any) – Additional keyword arguments passed by Locust.
- Return type:
None
- class locust_telemetry.recorders.json.handlers.JsonTelemetrySystemMetricsHandler(output, env)[source]
Bases:
BaseSystemMetricsHandlerSystem metrics handler for JSON telemetry.
Responsibilities
Periodically capture process-level metrics (CPU and memory usage).
Forward metrics to the JSON output handler.
Run metrics collection in a background greenlet for non-blocking execution.
- Parameters:
output (BaseOutputHandler)
env (Environment)
- class locust_telemetry.recorders.json.handlers.JsonTelemetryRequestHandler(output, env)[source]
Bases:
BaseRequestHandlerJSON telemetry handler for Locust request events/metrics.
This handler periodically collects aggregate request metrics and forwards them to the output handler in a format suitable for JSON logging. It also implements the RequestHandlerBase interface for individual request events, though in JSON telemetry no action is needed per-request.
- Parameters:
output (BaseOutputHandler)
env (Environment)
- _request_metrics_gevent
Background greenlet for periodically collecting request metrics.
- Type:
Optional[gevent.Greenlet]
- start()[source]
Start periodic request metrics collection.
Spawns a background greenlet that logs aggregate request statistics at the configured interval.
- Return type:
None
- stop()[source]
Stop request metrics collection.
Terminates the greenlet collecting request metrics. Logs a warning if the collection loop was never started.
- Return type:
None
- on_request(*args, **kwargs)[source]
Handler for individual Locust request events.
For JSON telemetry, per-request handling is not needed, so this is intentionally left empty.
- Parameters:
*args (Any) – Positional arguments from Locust request events.
**kwargs (Any) – Keyword arguments from Locust request events.
- Return type:
None
This module defines the LocustJsonRecorderPlugin, which integrates telemetry recording into Locust runs. It initializes master and worker telemetry recorders to capture lifecycle events, request statistics, and worker system metrics.
- class locust_telemetry.recorders.json.plugin.LocustJsonRecorderPlugin[source]
Bases:
BaseRecorderPluginCore telemetry recorder plugin for Locust.
Responsibilities
Register CLI arguments for telemetry configuration.
Load master-side telemetry recorders.
Load worker-side telemetry recorders.
- add_test_metadata()[source]
This recorder plugin doesn’t need any metadata other than the default available at config.DEFAULT_ENVIRONMENT_METADATA
- Return type:
- add_cli_arguments(group)[source]
Register CLI arguments for this telemetry recorder plugin.
- Parameters:
group (Any (_ArgumentGroup)) – The argument group to which telemetry recorder options are added.
- Return type:
None
JSON telemetry recorders for Locust.
This module defines master and worker recorder classes that integrate with the Locust telemetry system and use JSON-specific handlers to capture and log lifecycle events, system metrics, request metrics, and output.
- class locust_telemetry.recorders.json.recorder.LocustJsonMasterNodeRecorder(*args, **kwargs)[source]
Bases:
MasterNodeRecorderJSON-enabled telemetry recorder for the Locust master node.
This class extends the base
MasterNodeRecorderto provide JSON-based telemetry export. It sets up JSON-specific handlers for system metrics, request metrics, lifecycle events, and output handling.
- class locust_telemetry.recorders.json.recorder.LocustJsonWorkerNodeRecorder(*args, **kwargs)[source]
Bases:
WorkerNodeRecorderJSON-enabled telemetry recorder for Locust worker nodes.
This class extends the base
WorkerNodeRecorderto provide JSON-based telemetry export. It sets up JSON-specific handlers for system metrics, request metrics, lifecycle events, and output handling.
- exception locust_telemetry.recorders.otel.exceptions.OtelMetricNotRegisteredError[source]
Bases:
Exception
- exception locust_telemetry.recorders.otel.exceptions.OtelMetricAlreadyRegisteredError[source]
Bases:
Exception
OpenTelemetry handlers for Locust.
This module provides handler implementations for lifecycle events, system metrics, request metrics, and output in the context of OpenTelemetry. These handlers are used by OTEL recorders for both master and worker nodes to collect and export telemetry data to an OTLP endpoint.
- class locust_telemetry.recorders.otel.handlers.OtelOutputHandler(env)[source]
Bases:
BaseOutputHandlerOpenTelemetry output handler.
Responsible for recording lifecycle events and metrics using registered OTEL instruments.
Initialize the output handler.
- Parameters:
env (Environment) – Locust Environment instance containing the OpenTelemetry meter and instrument registry.
- __init__(env)[source]
Initialize the output handler.
- Parameters:
env (Environment) – Locust Environment instance containing the OpenTelemetry meter and instrument registry.
- record_event(tl_type, *args, **kwargs)[source]
Record a lifecycle event as a counter with event type as attribute.
- Parameters:
tl_type (TelemetryEventsEnum) – The lifecycle event being recorded (e.g., test.start, test.stop).
*args (Any) – Additional unused arguments.
**kwargs (Any) – Attributes to attach to the recorded metric.
- Return type:
None
- record_metrics(tl_type, *args, **kwargs)[source]
Record request or custom metrics.
- Parameters:
tl_type (TelemetryMetricsEnum) – The metric being recorded (e.g., request_success).
*args (Any) – Positional arguments containing metric values (e.g., response time).
**kwargs (Any) – Attributes to attach to the recorded metric.
- Return type:
None
- class locust_telemetry.recorders.otel.handlers.OtelLifecycleHandler(output, env)[source]
Bases:
BaseLifecycleHandlerOpenTelemetry lifecycle handler.
Extends the base lifecycle handler to register OTEL instruments for test events and user counts.
Initialize the lifecycle handler and register instruments.
- Parameters:
output (OtelOutputHandler) – The OTEL output handler for recording metrics.
env (Environment) – Locust Environment instance.
- __init__(output, env)[source]
Initialize the lifecycle handler and register instruments.
- Parameters:
output (OtelOutputHandler) – The OTEL output handler for recording metrics.
env (Environment) – Locust Environment instance.
- property instruments: Sequence[InstrumentSpec]
All the instruments that is required by this handler
- class locust_telemetry.recorders.otel.handlers.OtelSystemMetricsHandler(output, env)[source]
Bases:
BaseSystemMetricsHandlerOpenTelemetry handler for system-level metrics.
Collects CPU usage, memory usage, and network I/O using psutil and reports them via Observable Gauges.
Initialize the system metrics handler.
- Parameters:
output (OtelOutputHandler) – Reference to the output handler for recording metrics.
env (Environment) – Locust Environment instance.
- __init__(output, env)[source]
Initialize the system metrics handler.
- Parameters:
output (OtelOutputHandler) – Reference to the output handler for recording metrics.
env (Environment) – Locust Environment instance.
- property instruments: Sequence[InstrumentSpec]
All the instruments that is required by this handler
- class locust_telemetry.recorders.otel.handlers.OtelRequestHandler(output, env)[source]
Bases:
BaseRequestHandlerOpenTelemetry handler for request-level metrics.
Registers histograms for request success and failure durations, and records metrics for each request event.
Initialize the request metrics handler.
- Parameters:
output (OtelOutputHandler) – Reference to the output handler for recording metrics.
env (Environment) – Locust Environment instance.
- __init__(output, env)[source]
Initialize the request metrics handler.
- Parameters:
output (OtelOutputHandler) – Reference to the output handler for recording metrics.
env (Environment) – Locust Environment instance.
- property instruments: Sequence[InstrumentSpec]
All the instruments that is required by this handler
- on_request(*args, **kwargs)[source]
Handle a request event and record request duration.
- Parameters:
*args (Any) – Additional unused arguments.
**kwargs (Any) – Keyword arguments containing request metadata, such as response_time, name, and exception.
- Return type:
None
- class locust_telemetry.recorders.otel.otel.InstrumentRegistry(meter)[source]
Bases:
objectRegistry for managing OpenTelemetry metric instruments.
This class provides a structured way to register and retrieve metric instruments, ensuring uniqueness and consistency across the application.
Initialize the instrument registry.
- Parameters:
meter (metrics.Meter) – The OpenTelemetry meter used to create instruments.
- __init__(meter)[source]
Initialize the instrument registry.
- Parameters:
meter (metrics.Meter) – The OpenTelemetry meter used to create instruments.
- extend(items)[source]
Register multiple metric instruments in the registry.
- Parameters:
items (Sequence[InstrumentSpec]) – A list of instrument specifications to register.
- Raises:
ValueError – If a metric is already registered.
- Return type:
None
- get(key)[source]
Retrieve a registered instrument by its metric identifier.
- Parameters:
key (TelemetryEventsEnum | TelemetryMetricsEnum) – The metric identifier.
- Returns:
The registered instrument, or None if not found.
- Return type:
h.InstrumentType
- locust_telemetry.recorders.otel.otel.configure_otel(environment)[source]
Configure and initialize OpenTelemetry metrics for a Locust environment.
This function: - Creates an OTLP exporter (gRPC). - Sets up a periodic metrics reader with the configured export interval. - Configures a MeterProvider with the given resource attributes. - Registers the meter provider globally. - Instantiates and attaches an InstrumentRegistry to the environment.
- Parameters:
environment (Any)
configuration. (Locust environment object containing parsed options for OTEL)
- Returns:
The modified environment object with otel_registry attached.
- Return type:
Any
- class locust_telemetry.recorders.otel.plugin.LocustOtelRecorderPlugin[source]
Bases:
BaseRecorderPluginOpenTelemetry Recorder Plugin for Locust.
This plugin integrates Locust with OpenTelemetry (OTel), enabling the export of metrics and lifecycle events to an OTLP endpoint. It provides recorder implementations for both master and worker nodes.
Features
Registers CLI arguments for OTLP exporter configuration.
Instantiates master and worker OTel recorders.
Supports trace context injection into requests for downstream correlation.
Notes
Master node uses
LocustOtelMasterNodeRecorder.Worker nodes use
LocustOtelWorkerNodeRecorder.Exporter configuration can be provided via CLI or environment variables.
- add_test_metadata()[source]
Provide test-level metadata to attach to OTel metrics and traces.
- Returns:
Key-value metadata pairs. Defaults to an empty dictionary.
- Return type:
Dict[str, Any]
- add_cli_arguments(group)[source]
Register CLI arguments for configuring the OpenTelemetry OTLP exporter.
- Parameters:
group (argparse._ArgumentGroup) – CLI argument group for plugin-specific arguments.
- Return type:
None
Notes
Arguments support environment variable overrides.
- load_master_recorders(environment, **kwargs)[source]
Initialize and load the OTel recorder for the master node.
- Parameters:
environment (Environment) – Locust runtime environment.
**kwargs (Any) – Additional plugin arguments.
- Return type:
None
OpenTelemetry recorders for Locust.
This module defines master and worker recorder classes that integrate with the Locust telemetry system using OpenTelemetry (OTEL). These recorders configure an OTLP exporter, register metric readers, and use OTEL-specific handlers to capture and export lifecycle events, system metrics, request metrics, and output.
- class locust_telemetry.recorders.otel.recorder.LocustOtelMasterNodeRecorder(*args, **kwargs)[source]
Bases:
MasterNodeRecorderOpenTelemetry-enabled telemetry recorder for the Locust master node.
This class extends the base
MasterNodeRecorderto add OpenTelemetry metric collection and export. It sets up OTEL-specific handlers for system metrics, request metrics, lifecycle events, and output handling. Additionally, it initializes the OTLP exporter and meter provider viaconfigure_otel().Notes
Currently, this class does not override any methods, but it exists as a specialization hook for future master-specific behavior.
- class locust_telemetry.recorders.otel.recorder.LocustOtelWorkerNodeRecorder(*args, **kwargs)[source]
Bases:
WorkerNodeRecorderOpenTelemetry-enabled telemetry recorder for Locust worker nodes.
This class extends the base
WorkerNodeRecorderto add OpenTelemetry metric collection and export. It sets up OTEL-specific handlers for system metrics, request metrics, lifecycle events, and output handling. Additionally, it initializes the OTLP exporter and meter provider viaconfigure_otel().Initialize the worker recorder and attach request listeners.
- Parameters:
*args (Any) – Positional arguments passed to the base class initializer.
**kwargs (Any) – Keyword arguments passed to the base class initializer.
- __init__(*args, **kwargs)[source]
Initialize the worker recorder and attach request listeners.
- Parameters:
*args (Any) – Positional arguments passed to the base class initializer.
**kwargs (Any) – Keyword arguments passed to the base class initializer.
- on_request(*args, **kwargs)[source]
Handle a request event from Locust and record it as a histogram.
This method is registered as an event listener on
env.events.request.- Parameters:
*args (Any) – Positional arguments forwarded from the Locust request event.
**kwargs (Any) – Keyword arguments forwarded from the Locust request event, typically including
name,response_time, andexceptionfields.