Interface MetricsCollector


@ThreadSafe public interface MetricsCollector
Contract for collecting operational metrics from Soklet.

Soklet's standard implementation, available via defaultInstance(), supports detailed histogram collection, connection accept/reject counters, immutable snapshots (via snapshot()), and provides Prometheus (text format v0.0.4) / OpenMetrics (1.0) export helpers for convenience. To disable metrics collection without a custom implementation, use disabledInstance().

If you prefer OpenTelemetry, Micrometer, or another metrics system for monitoring, you might choose to create your own implementation of this interface.

Example configuration:

SokletConfig config = SokletConfig.withServer(Server.fromPort(8080))
  // This is already the default; specifying it here is optional
  .metricsCollector(MetricsCollector.defaultInstance())
  .build();

To disable metrics collection entirely, specify Soklet's no-op implementation:

SokletConfig config = SokletConfig.withServer(Server.fromPort(8080))
  // Use this instead of null to disable metrics collection
  .metricsCollector(MetricsCollector.disabledInstance())
  .build();

All methods must be:

  • Thread-safe — called concurrently from multiple request threads
  • Non-blocking — should not perform I/O or acquire locks that might contend
  • Failure-tolerant — exceptions are caught and logged, never break request handling

Example usage:

@GET("/metrics")
public MarshaledResponse getMetrics(@NonNull MetricsCollector metricsCollector) {
  SnapshotTextOptions options = SnapshotTextOptions
    .fromMetricsFormat(MetricsFormat.PROMETHEUS);

  String body = metricsCollector.snapshotText(options).orElse(null);

  if (body == null)
    return MarshaledResponse.fromStatusCode(204);

  return MarshaledResponse.withStatusCode(200)
    .headers(Map.of("Content-Type", Set.of("text/plain; charset=UTF-8")))
    .body(body.getBytes(StandardCharsets.UTF_8))
    .build();
}

See https://www.soklet.com/docs/metrics-collection for detailed documentation.

Author:
Mark Allen