Interface MetricsCollector
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
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic final classA thread-safe histogram with fixed bucket boundaries.static final classImmutable snapshot of aMetricsCollector.Histogram.static enumText format to use forsnapshotText(SnapshotTextOptions).static final recordKey for request read failures grouped by reason.static final recordKey for request rejections grouped by reason.static enumIndicates whether a request was matched to aResourcePathDeclaration.static final recordKey for metrics grouped by HTTP method and route match information.static final recordKey for metrics grouped by HTTP method, route match information, and status class (e.g. 2xx).static final recordKey for metrics grouped by Server-Sent Event comment type, route match information, and drop reason.static final recordKey for metrics grouped by Server-Sent Event comment type, route match information, and enqueue outcome.static final recordKey for metrics grouped by Server-Sent Event comment type and route match information.static enumReasons a Server-Sent Event payload or comment was dropped before it could be written.static enumOutcomes for a Server-Sent Event enqueue attempt.static final recordKey for metrics grouped by Server-Sent Event route match information and drop reason.static final recordKey for metrics grouped by Server-Sent Event route match information and enqueue outcome.static final recordKey for metrics grouped by Server-Sent Event route match information and handshake failure reason.static final recordKey for metrics grouped by Server-Sent Event route match information.static final recordKey for metrics grouped by Server-Sent Event route match information and termination reason.static final classImmutable snapshot of collected metrics.static final classOptions for rendering a textual metrics snapshot. -
Method Summary
Modifier and TypeMethodDescriptionstatic @NonNull MetricsCollectorAcquires a threadsafeMetricsCollectorinstance with sensible defaults.default voiddidAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called after a server accepts a new TCP connection.default voiddidAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called after a request is accepted for application-level handling.default voiddidBroadcastServerSentEvent(@NonNull ResourcePathDeclaration route, int attempted, int enqueued, int dropped) Called after a broadcast attempt for a Server-Sent Event payload.default voiddidBroadcastServerSentEventComment(@NonNull ResourcePathDeclaration route, @NonNull ServerSentEventComment.CommentType commentType, int attempted, int enqueued, int dropped) Called after a broadcast attempt for a Server-Sent Event comment payload.default voiddidDropServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent, @NonNull MetricsCollector.ServerSentEventDropReason reason, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE event is dropped before it can be enqueued for delivery.default voiddidDropServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment, @NonNull MetricsCollector.ServerSentEventDropReason reason, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE comment is dropped before it can be enqueued for delivery.default voiddidEstablishServerSentEventConnection(@NonNull ServerSentEventConnection serverSentEventConnection) Called after an SSE connection is established.default voiddidFailToAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @NonNull ConnectionRejectionReason reason, @Nullable Throwable throwable) Called after a server fails to accept a new TCP connection.default voiddidFailToAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestRejectionReason reason, @Nullable Throwable throwable) Called when a request fails to be accepted before application-level handling begins.default voiddidFailToEstablishServerSentEventConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull ServerSentEventConnection.HandshakeFailureReason reason, @Nullable Throwable throwable) Called if an SSE connection fails to establish.default voiddidFailToReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestReadFailureReason reason, @Nullable Throwable throwable) Called when a request could not be read or parsed into a validRequest.default voiddidFailToWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration, @NonNull Throwable throwable) Called after response data fails to write.default voiddidFailToWriteServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent, @NonNull Duration writeDuration, @NonNull Throwable throwable, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE event fails to write.default voiddidFailToWriteServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment, @NonNull Duration writeDuration, @NonNull Throwable throwable, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE comment fails to write.default voiddidFinishRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration duration, @NonNull List<@NonNull Throwable> throwables) Called after a request finishes processing.default voiddidReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request was successfully read or parsed into a validRequest.default voiddidStartRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod) Called as soon as a request is received and a Resource Method has been resolved to handle it.default voiddidTerminateServerSentEventConnection(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull Duration connectionDuration, @NonNull ServerSentEventConnection.TerminationReason terminationReason, @Nullable Throwable throwable) Called after an SSE connection is terminated.default voiddidWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration) Called after response data is written.default voiddidWriteServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent, @NonNull Duration writeDuration, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE event is written.default voiddidWriteServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment, @NonNull Duration writeDuration, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE comment is written.static @NonNull MetricsCollectorAcquires a threadsafeMetricsCollectorinstance that performs no work.default voidreset()Resets any in-memory metrics state, if supported.default @NonNull Optional<MetricsCollector.Snapshot> snapshot()Returns a snapshot of metrics collected so far, if supported.Returns a text snapshot of metrics collected so far, if supported.default voidwillAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called when a server is about to accept a new TCP connection.default voidwillAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request is about to be accepted for application-level handling.default voidwillEstablishServerSentEventConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod) Called before an SSE connection is established.default voidwillReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when Soklet is about to read or parse a request into a validRequest.default voidwillTerminateServerSentEventConnection(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventConnection.TerminationReason terminationReason, @Nullable Throwable throwable) Called before an SSE connection is terminated.default voidwillWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse) Called before response data is written.default voidwillWriteServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent) Called before an SSE event is written.default voidwillWriteServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment) Called before an SSE comment is written.
-
Method Details
-
willAcceptConnection
default void willAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called when a server is about to accept a new TCP connection.- Parameters:
serverType- the server type that is accepting the connectionremoteAddress- the best-effort remote address, ornullif unavailable
-
didAcceptConnection
default void didAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called after a server accepts a new TCP connection.- Parameters:
serverType- the server type that accepted the connectionremoteAddress- the best-effort remote address, ornullif unavailable
-
didFailToAcceptConnection
default void didFailToAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @NonNull ConnectionRejectionReason reason, @Nullable Throwable throwable) Called after a server fails to accept a new TCP connection.- Parameters:
serverType- the server type that failed to accept the connectionremoteAddress- the best-effort remote address, ornullif unavailablereason- the failure reasonthrowable- an optional underlying cause, ornullif not applicable
-
willAcceptRequest
default void willAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request is about to be accepted for application-level handling.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didAcceptRequest
default void didAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called after a request is accepted for application-level handling.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didFailToAcceptRequest
default void didFailToAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestRejectionReason reason, @Nullable Throwable throwable) Called when a request fails to be accepted before application-level handling begins.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailablereason- the rejection reasonthrowable- an optional underlying cause, ornullif not applicable
-
willReadRequest
default void willReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when Soklet is about to read or parse a request into a validRequest.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didReadRequest
default void didReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request was successfully read or parsed into a validRequest.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didFailToReadRequest
default void didFailToReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestReadFailureReason reason, @Nullable Throwable throwable) Called when a request could not be read or parsed into a validRequest.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailablereason- the failure reasonthrowable- an optional underlying cause, ornullif not applicable
-
didStartRequestHandling
default void didStartRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod) Called as soon as a request is received and a Resource Method has been resolved to handle it.- Parameters:
serverType- the server type that received the request
-
didFinishRequestHandling
default void didFinishRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration duration, @NonNull List<@NonNull Throwable> throwables) Called after a request finishes processing. -
willWriteResponse
default void willWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse) Called before response data is written. -
didWriteResponse
default void didWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration) Called after response data is written. -
didFailToWriteResponse
default void didFailToWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration, @NonNull Throwable throwable) Called after response data fails to write. -
willEstablishServerSentEventConnection
default void willEstablishServerSentEventConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod) Called before an SSE connection is established. -
didEstablishServerSentEventConnection
default void didEstablishServerSentEventConnection(@NonNull ServerSentEventConnection serverSentEventConnection) Called after an SSE connection is established. -
didFailToEstablishServerSentEventConnection
default void didFailToEstablishServerSentEventConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull ServerSentEventConnection.HandshakeFailureReason reason, @Nullable Throwable throwable) Called if an SSE connection fails to establish.- Parameters:
reason- the handshake failure reasonthrowable- an optional underlying cause, ornullif not applicable
-
willTerminateServerSentEventConnection
default void willTerminateServerSentEventConnection(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventConnection.TerminationReason terminationReason, @Nullable Throwable throwable) Called before an SSE connection is terminated. -
didTerminateServerSentEventConnection
default void didTerminateServerSentEventConnection(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull Duration connectionDuration, @NonNull ServerSentEventConnection.TerminationReason terminationReason, @Nullable Throwable throwable) Called after an SSE connection is terminated. -
willWriteServerSentEvent
default void willWriteServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent) Called before an SSE event is written. -
didWriteServerSentEvent
default void didWriteServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent, @NonNull Duration writeDuration, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE event is written.- Parameters:
serverSentEventConnection- the connection the event was written toserverSentEvent- the event that was writtenwriteDuration- how long it took to write the eventdeliveryLag- elapsed time between enqueue and write start, ornullif unknownpayloadBytes- size of the serialized payload in bytes, ornullif unknownqueueDepth- number of queued elements remaining at write time, ornullif unknown
-
didFailToWriteServerSentEvent
default void didFailToWriteServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent, @NonNull Duration writeDuration, @NonNull Throwable throwable, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE event fails to write.- Parameters:
serverSentEventConnection- the connection the event was written toserverSentEvent- the event that was writtenwriteDuration- how long it took to attempt the writethrowable- the failure causedeliveryLag- elapsed time between enqueue and write start, ornullif unknownpayloadBytes- size of the serialized payload in bytes, ornullif unknownqueueDepth- number of queued elements remaining at write time, ornullif unknown
-
willWriteServerSentEventComment
default void willWriteServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment) Called before an SSE comment is written. -
didWriteServerSentEventComment
default void didWriteServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment, @NonNull Duration writeDuration, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE comment is written.- Parameters:
serverSentEventConnection- the connection the comment was written toserverSentEventComment- the comment that was writtenwriteDuration- how long it took to write the commentdeliveryLag- elapsed time between enqueue and write start, ornullif unknownpayloadBytes- size of the serialized payload in bytes, ornullif unknownqueueDepth- number of queued elements remaining at write time, ornullif unknown
-
didFailToWriteServerSentEventComment
default void didFailToWriteServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment, @NonNull Duration writeDuration, @NonNull Throwable throwable, @Nullable Duration deliveryLag, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE comment fails to write.- Parameters:
serverSentEventConnection- the connection the comment was written toserverSentEventComment- the comment that was writtenwriteDuration- how long it took to attempt the writethrowable- the failure causedeliveryLag- elapsed time between enqueue and write start, ornullif unknownpayloadBytes- size of the serialized payload in bytes, ornullif unknownqueueDepth- number of queued elements remaining at write time, ornullif unknown
-
didDropServerSentEvent
default void didDropServerSentEvent(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEvent serverSentEvent, @NonNull MetricsCollector.ServerSentEventDropReason reason, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE event is dropped before it can be enqueued for delivery.- Parameters:
serverSentEventConnection- the connection the event was targetingserverSentEvent- the event that was droppedreason- the drop reasonpayloadBytes- size of the serialized payload in bytes, ornullif unknownqueueDepth- number of queued elements at drop time, ornullif unknown
-
didDropServerSentEventComment
default void didDropServerSentEventComment(@NonNull ServerSentEventConnection serverSentEventConnection, @NonNull ServerSentEventComment serverSentEventComment, @NonNull MetricsCollector.ServerSentEventDropReason reason, @Nullable Integer payloadBytes, @Nullable Integer queueDepth) Called after an SSE comment is dropped before it can be enqueued for delivery.- Parameters:
serverSentEventConnection- the connection the comment was targetingserverSentEventComment- the comment that was droppedreason- the drop reasonpayloadBytes- size of the serialized payload in bytes, ornullif unknownqueueDepth- number of queued elements at drop time, ornullif unknown
-
didBroadcastServerSentEvent
default void didBroadcastServerSentEvent(@NonNull ResourcePathDeclaration route, int attempted, int enqueued, int dropped) Called after a broadcast attempt for a Server-Sent Event payload.- Parameters:
route- the route declaration that was broadcast toattempted- number of connections targetedenqueued- number of connections for which enqueue succeededdropped- number of connections for which enqueue failed
-
didBroadcastServerSentEventComment
default void didBroadcastServerSentEventComment(@NonNull ResourcePathDeclaration route, @NonNull ServerSentEventComment.CommentType commentType, int attempted, int enqueued, int dropped) Called after a broadcast attempt for a Server-Sent Event comment payload.- Parameters:
route- the route declaration that was broadcast tocommentType- the comment typeattempted- number of connections targetedenqueued- number of connections for which enqueue succeededdropped- number of connections for which enqueue failed
-
snapshot
Returns a snapshot of metrics collected so far, if supported.- Returns:
- an optional metrics snapshot
-
snapshotText
default @NonNull Optional<String> snapshotText(@NonNull MetricsCollector.SnapshotTextOptions options) Returns a text snapshot of metrics collected so far, if supported.The default collector supports Prometheus (text format v0.0.4) and OpenMetrics (1.0) text exposition formats.
- Parameters:
options- the snapshot rendering options- Returns:
- a textual metrics snapshot, or
Optional.empty()if unsupported
-
reset
Resets any in-memory metrics state, if supported. -
defaultInstance
Acquires a threadsafeMetricsCollectorinstance with sensible defaults.This method is guaranteed to return a new instance.
- Returns:
- a
MetricsCollectorwith default settings
-
disabledInstance
Acquires a threadsafeMetricsCollectorinstance that performs no work.This method is useful when you want to explicitly disable metrics collection without writing your own implementation.
The returned instance is guaranteed to be a JVM-wide singleton.
- Returns:
- a no-op
MetricsCollector
-