Core Concepts
Request Lifecycle
Soklet provides two lifecycle hooks:
- RequestInterceptor for adjusting request flow (wrapping or intercepting)
- LifecycleObserver for read-only observation of system and request events
They're useful for tasks like:
- Logging requests and responses
- Performing authentication and authorization
- Modifying requests/responses before downstream processing occurs
- Wrapping downstream code in a database transaction
- Monitoring unexpected errors that occur during internal processing (see Event Logging)
This is similar to the Jakarta EE Servlet Filter concept, but provides additional functionality beyond "wrap the whole request".
Request Interceptor
Request Wrapping
Wraps synchronous request handling, including Resource Method execution and response handoff to the transport. HTTP streaming body production has a separate lifetime; the wrapping scope does not cover it. For a more fine-grained approach, see Request Intercepting.
Wrapping happens before Soklet resolves which Resource Method should handle the request. This means you can rewrite the HTTP method or path by returning a modified request via the consumer and Soklet will route using the wrapped request. You must call requestProcessor.accept(...) exactly once before returning; otherwise Soklet logs an error and returns a 500 response.
Wrapping a request is useful when you'd like to store off request-scoped information that needs to be made easily accessible to other parts of the system - for example, a request's Locale and ZoneId.
To implement, a useful scoping mechanism is Java's ScopedValue<T> (Java 25+) or ThreadLocal<T>. The former is demonstrated below.
// Special scoped value so anyone can access the current Locale.
// For Java < 25, use ThreadLocal instead
public static final ScopedValue<Locale> CURRENT_LOCALE;
// Spin up the ScopedValue (or ThreadLocal)
static {
CURRENT_LOCALE = ScopedValue.newInstance();
}
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).requestInterceptor(new RequestInterceptor() {
@Override
public void wrapRequest(
@NonNull ServerType serverType,
@NonNull Request request,
@NonNull Consumer<Request> requestProcessor
) {
// Make the locale accessible by other code during this request...
Locale locale = request.getLocales().stream().findFirst().orElse(Locale.ENGLISH);
// ...by binding it to a ScopedValue (or ThreadLocal).
ScopedValue.where(CURRENT_LOCALE, locale).run(() -> {
// You must call this so downstream processing can proceed
requestProcessor.accept(request);
});
}
}).build();
// Special scoped value so anyone can access the current Locale.
// For Java < 25, use ThreadLocal instead
public static final ScopedValue<Locale> CURRENT_LOCALE;
// Spin up the ScopedValue (or ThreadLocal)
static {
CURRENT_LOCALE = ScopedValue.newInstance();
}
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).requestInterceptor(new RequestInterceptor() {
@Override
public void wrapRequest(
@NonNull ServerType serverType,
@NonNull Request request,
@NonNull Consumer<Request> requestProcessor
) {
// Make the locale accessible by other code during this request...
Locale locale = request.getLocales().stream().findFirst().orElse(Locale.ENGLISH);
// ...by binding it to a ScopedValue (or ThreadLocal).
ScopedValue.where(CURRENT_LOCALE, locale).run(() -> {
// You must call this so downstream processing can proceed
requestProcessor.accept(request);
});
}
}).build();
Then, elsewhere in your code during synchronous request handling:
class ExampleService {
void accessCurrentLocale() {
// You now have access to the Locale bound to the logical scope
// (or Thread) without having to pass it down the call stack
Locale locale = CURRENT_LOCALE.orElse(Locale.getDefault());
}
}
class ExampleService {
void accessCurrentLocale() {
// You now have access to the Locale bound to the logical scope
// (or Thread) without having to pass it down the call stack
Locale locale = CURRENT_LOCALE.orElse(Locale.getDefault());
}
}
The built-in HTTP server runs streaming writers and source factories on a separate producer thread. Soklet does not propagate these ScopedValue or ThreadLocal bindings, transactions, or ambient tracing scopes. Production can overlap remaining wrapping or observer callbacks; there is no guarantee that all those callbacks return before the producer starts. Capture required immutable values in the Resource Method and explicitly bind context around producer work when helpers need it. See Streaming Context and Transactions for a complete example and the simulator's execution differences.
References:
Request Intercepting
Conceptually, when a request comes in, Soklet will:
- Invoke the appropriate Resource Method to acquire a response
- Hand the response to the transport for delivery
Request Intercepting provides programmatic control over those two steps.
Example use cases are:
- Wrapping Resource Methods with a database transaction (e.g. to ensure atomicity)
- Customizing responses prior to sending over the wire
For a more coarse-grained approach, see Request Wrapping.
You must call responseWriter.accept(...) exactly once before returning; otherwise Soklet logs an error and returns a 500 response.
ThreadLocal<AtomicBoolean> requestFailed = new ThreadLocal<>();
ResponseMarshaler defaultResponses = ResponseMarshaler.defaultInstance();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).responseMarshaler(ResponseMarshaler.builder()
.throwableHandler((request, throwable, resourceMethod) -> {
// Response generation handles the Throwable instead of propagating it.
AtomicBoolean failed = requestFailed.get();
if (failed != null)
failed.set(true);
return defaultResponses.forThrowable(request, throwable, resourceMethod);
}).build()
).requestInterceptor(new RequestInterceptor() {
@Override
public void interceptRequest(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull Function<Request, MarshaledResponse> responseGenerator,
@NonNull Consumer<MarshaledResponse> responseWriter
) {
MyDatabase.INSTANCE.beginTransaction();
AtomicBoolean failed = new AtomicBoolean();
requestFailed.set(failed);
boolean transactionFinished = false;
MarshaledResponse response;
try {
response = responseGenerator.apply(request);
if (failed.get())
MyDatabase.INSTANCE.rollbackTransaction();
else
MyDatabase.INSTANCE.commitTransaction();
transactionFinished = true;
} finally {
try {
// Also roll back if generation or committing unexpectedly throws.
if (!transactionFinished)
MyDatabase.INSTANCE.rollbackTransaction();
} finally {
requestFailed.remove();
}
}
// The transaction is finished before transport delivery begins.
responseWriter.accept(response);
}
}).build();
ThreadLocal<AtomicBoolean> requestFailed = new ThreadLocal<>();
ResponseMarshaler defaultResponses = ResponseMarshaler.defaultInstance();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).responseMarshaler(ResponseMarshaler.builder()
.throwableHandler((request, throwable, resourceMethod) -> {
// Response generation handles the Throwable instead of propagating it.
AtomicBoolean failed = requestFailed.get();
if (failed != null)
failed.set(true);
return defaultResponses.forThrowable(request, throwable, resourceMethod);
}).build()
).requestInterceptor(new RequestInterceptor() {
@Override
public void interceptRequest(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull Function<Request, MarshaledResponse> responseGenerator,
@NonNull Consumer<MarshaledResponse> responseWriter
) {
MyDatabase.INSTANCE.beginTransaction();
AtomicBoolean failed = new AtomicBoolean();
requestFailed.set(failed);
boolean transactionFinished = false;
MarshaledResponse response;
try {
response = responseGenerator.apply(request);
if (failed.get())
MyDatabase.INSTANCE.rollbackTransaction();
else
MyDatabase.INSTANCE.commitTransaction();
transactionFinished = true;
} finally {
try {
// Also roll back if generation or committing unexpectedly throws.
if (!transactionFinished)
MyDatabase.INSTANCE.rollbackTransaction();
} finally {
requestFailed.remove();
}
}
// The transaction is finished before transport delivery begins.
responseWriter.accept(response);
}
}).build();
responseGenerator.apply(request) catches Resource Method failures and returns the response selected by ResponseMarshaler.forThrowable(...); the surrounding transaction does not see the original exception. Here the throwable handler marks failures handled during response generation, and the interceptor rolls back when that flag is set. This transaction ends before response postprocessing and transport delivery: a later postProcessor failure cannot undo its commit. A handler that ignores timeout interruption can also finish and commit after the client has received a timeout response; use database deadlines and cooperative cancelation for that work. An intentionally returned HTTP error status does not by itself indicate a failed transaction. The example uses java.util.concurrent.atomic.AtomicBoolean; adapt the transaction calls to your database library.
For a streaming response, responseGenerator.apply(request) returns a body descriptor; it does not run the writer inside this transaction. Complete the required data access before committing, or open a separate bounded transaction during production. Do not return a writer that depends on a cursor or lazy entity whose transaction ends here. Neither responseWriter.accept(...) nor these interceptor scopes cover the complete stream lifetime.
References:
Lifecycle Observer
LifecycleObserver is the right hook for read-only request, stream, SSE, and MCP observation: tracing, audit events, structured logging, and cleanup notifications. For aggregate counters, gauges, and histograms, prefer MetricsCollector instead.
Configure one observer with SokletConfig.Builder::lifecycleObserver, or configure several observers in registration order with SokletConfig.Builder::lifecycleObservers. Calling lifecycleObserver(null) or lifecycleObservers(null) clears the observer list.
Configuring a custom observer replaces the default stderr logger. Include LifecycleObserver.defaultInstance() in your observer collection, or implement didReceiveLogEvent, to retain application log output. The single-observer examples below require that choice.
SokletConfig config = SokletConfig.withHttpServer(HttpServer.fromPort(8080))
.lifecycleObservers(List.of(
new AuditLifecycleObserver(),
new TracingLifecycleObserver()
))
.build();
SokletConfig config = SokletConfig.withHttpServer(HttpServer.fromPort(8080))
.lifecycleObservers(List.of(
new AuditLifecycleObserver(),
new TracingLifecycleObserver()
))
.build();
Soklet Start/Stop
Observe startup and shutdown of a Soklet instance. These lifecycle notifications are delivered asynchronously on a bounded dispatcher. Returning from run(...) or either await method does not guarantee that every observer callback has finished. A willStart or willStop callback cannot enforce a prerequisite for the corresponding lifecycle phase.
Complete required startup work before calling Soklet.run(config). Its return is the readiness boundary; use awaitShutdown() or awaitShutdownAsync() to observe full finalization. Required application cleanup belongs in a bounded ShutdownCleanup supplied to run; it is eligible only after complete core shutdown. See startup and cleanup examples. The observer worker is a daemon, so pending notifications may be lost at JVM exit. Aggregate callbacks receive no lifecycle owner; capture application identity in a per-application observer instance.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willStartSoklet() {
System.out.println("Soklet startup was requested.");
}
@Override
public void didStartSoklet() {
// Soklet has fully started.
// HttpServer (and optionally SSE server) are running
System.out.println("Soklet started.");
}
@Override
public void didFailToStartSoklet(
@NonNull Throwable throwable
) {
System.err.println("Soklet failed to start.");
throwable.printStackTrace();
}
@Override
public void willStopSoklet() {
System.out.println("Soklet shutdown was requested.");
}
@Override
public void didStopSoklet(
@NonNull ShutdownResult shutdownResult
) {
// Soklet has published its immutable terminal result
System.out.printf("Soklet stopped: %s%n", shutdownResult);
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willStartSoklet() {
System.out.println("Soklet startup was requested.");
}
@Override
public void didStartSoklet() {
// Soklet has fully started.
// HttpServer (and optionally SSE server) are running
System.out.println("Soklet started.");
}
@Override
public void didFailToStartSoklet(
@NonNull Throwable throwable
) {
System.err.println("Soklet failed to start.");
throwable.printStackTrace();
}
@Override
public void willStopSoklet() {
System.out.println("Soklet shutdown was requested.");
}
@Override
public void didStopSoklet(
@NonNull ShutdownResult shutdownResult
) {
// Soklet has published its immutable terminal result
System.out.printf("Soklet stopped: %s%n", shutdownResult);
}
}).build();
ShutdownResult and ShutdownComponentResult print compact, bounded diagnostics with dispositions, failure counts/presence and residual-activity categories. Printing them with %s does not invoke application Throwables or traverse retained objects. Use their typed accessors when you need failure details or a residual summary; these diagnostic strings are not a serialization format.
References:
LifecycleObserver::willStartSokletLifecycleObserver::didStartSokletLifecycleObserver::didFailToStartSokletLifecycleObserver::willStopSokletLifecycleObserver::didStopSoklet
HTTP Server Start/Stop
Observe startup and shutdown of the Soklet-managed HttpServer. These notifications use the same asynchronous lifecycle dispatcher described above; required startup and cleanup work belongs in the application lifecycle.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willStartHttpServer(@NonNull HttpServer httpServer) {
System.out.println("HTTP server startup was requested.");
}
@Override
public void didStartHttpServer(@NonNull HttpServer httpServer) {
// HTTP server has fully started up and is listening
System.out.println("HTTP server started.");
}
@Override
public void didFailToStartHttpServer(
@NonNull HttpServer httpServer,
@NonNull Throwable throwable
) {
System.err.println("HTTP server failed to start.");
throwable.printStackTrace();
}
@Override
public void willStopHttpServer(@NonNull HttpServer httpServer) {
System.out.println("HTTP server shutdown was requested.");
}
@Override
public void didStopHttpServer(
@NonNull HttpServer httpServer,
@NonNull ShutdownComponentResult shutdownComponentResult
) {
// HTTP server has published its terminal evidence
System.out.printf("HTTP server stopped: %s%n", shutdownComponentResult);
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willStartHttpServer(@NonNull HttpServer httpServer) {
System.out.println("HTTP server startup was requested.");
}
@Override
public void didStartHttpServer(@NonNull HttpServer httpServer) {
// HTTP server has fully started up and is listening
System.out.println("HTTP server started.");
}
@Override
public void didFailToStartHttpServer(
@NonNull HttpServer httpServer,
@NonNull Throwable throwable
) {
System.err.println("HTTP server failed to start.");
throwable.printStackTrace();
}
@Override
public void willStopHttpServer(@NonNull HttpServer httpServer) {
System.out.println("HTTP server shutdown was requested.");
}
@Override
public void didStopHttpServer(
@NonNull HttpServer httpServer,
@NonNull ShutdownComponentResult shutdownComponentResult
) {
// HTTP server has published its terminal evidence
System.out.printf("HTTP server stopped: %s%n", shutdownComponentResult);
}
}).build();
References:
LifecycleObserver::willStartHttpServerLifecycleObserver::didStartHttpServerLifecycleObserver::didFailToStartHttpServerLifecycleObserver::willStopHttpServerLifecycleObserver::didStopHttpServer
Connection Acceptance
These methods fire when Soklet is about to accept a TCP connection, after it accepts one, or when it fails to accept a connection attempt. Each callback provides a ServerType, a best-effort remote address, and (for failures) a ConnectionRejectionReason plus an optional exception.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willAcceptConnection(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress
) {
System.out.printf("Incoming %s connection from %s\n", serverType, remoteAddress);
}
@Override
public void didAcceptConnection(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress
) {
System.out.printf("Accepted %s connection from %s\n", serverType, remoteAddress);
}
@Override
public void didFailToAcceptConnection(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@NonNull ConnectionRejectionReason reason,
@Nullable Throwable throwable
) {
System.out.printf("Failed to accept %s connection from %s (%s)\n", serverType, remoteAddress, reason);
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willAcceptConnection(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress
) {
System.out.printf("Incoming %s connection from %s\n", serverType, remoteAddress);
}
@Override
public void didAcceptConnection(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress
) {
System.out.printf("Accepted %s connection from %s\n", serverType, remoteAddress);
}
@Override
public void didFailToAcceptConnection(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@NonNull ConnectionRejectionReason reason,
@Nullable Throwable throwable
) {
System.out.printf("Failed to accept %s connection from %s (%s)\n", serverType, remoteAddress, reason);
}
}).build();
References:
LifecycleObserver::willAcceptConnectionLifecycleObserver::didAcceptConnectionLifecycleObserver::didFailToAcceptConnection
Request Acceptance
These hooks fire as Soklet accepts requests for application-level handling and reads/parses them into Request instances.
Eight unparsed-request reasons cover malformed input, overlong targets, unsupported expectations, oversized headers, partial read timeouts, aggregate/body size limits, unsupported content encoding and decompression failures. If the rejection-detail task is admitted, LifecycleObserver::didRejectUnparsedRequest receives the immutable UnparsedRequest before ResponseMarshaler::forUnparsedRequest. They share the remaining handler timeout; the marshaler runs only while budget remains. The usual request acceptance/read callbacks do not run for that input. Idle read timeout and EOF before complete headers close quietly. Admission, shutdown and broken-socket failsafes bypass detailed customization. Saturation, callback timeout or invalid output uses a bodyless fallback. See Unparsed HTTP Requests.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willAcceptRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("About to accept request: %s%n", requestTarget);
}
@Override
public void didAcceptRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("Accepted request: %s%n", requestTarget);
}
@Override
public void didFailToAcceptRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget,
@NonNull RequestRejectionReason reason,
@Nullable Throwable throwable
) {
System.err.printf("Failed to accept request (%s): %s%n", reason, requestTarget);
}
@Override
public void willReadRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("About to read request: %s%n", requestTarget);
}
@Override
public void didReadRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("Read request: %s%n", requestTarget);
}
@Override
public void didFailToReadRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget,
@NonNull RequestReadFailureReason reason,
@Nullable Throwable throwable
) {
System.err.printf("Failed to read request (%s): %s%n", reason, requestTarget);
}
@Override
public void didRejectUnparsedRequest(
@NonNull UnparsedRequest unparsedRequest
) {
String remoteAddress = unparsedRequest.getRemoteAddress()
.map(Object::toString)
.orElse("<unknown>");
System.err.printf(
"Rejected unparsed %s input from %s after %d attributed bytes%s%n",
unparsedRequest.getReason(),
remoteAddress,
unparsedRequest.getObservedByteCount(),
unparsedRequest.isCaptureTruncated() ? " (capture truncated)" : ""
);
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willAcceptRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("About to accept request: %s%n", requestTarget);
}
@Override
public void didAcceptRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("Accepted request: %s%n", requestTarget);
}
@Override
public void didFailToAcceptRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget,
@NonNull RequestRejectionReason reason,
@Nullable Throwable throwable
) {
System.err.printf("Failed to accept request (%s): %s%n", reason, requestTarget);
}
@Override
public void willReadRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("About to read request: %s%n", requestTarget);
}
@Override
public void didReadRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget
) {
System.out.printf("Read request: %s%n", requestTarget);
}
@Override
public void didFailToReadRequest(
@NonNull ServerType serverType,
@Nullable InetSocketAddress remoteAddress,
@Nullable String requestTarget,
@NonNull RequestReadFailureReason reason,
@Nullable Throwable throwable
) {
System.err.printf("Failed to read request (%s): %s%n", reason, requestTarget);
}
@Override
public void didRejectUnparsedRequest(
@NonNull UnparsedRequest unparsedRequest
) {
String remoteAddress = unparsedRequest.getRemoteAddress()
.map(Object::toString)
.orElse("<unknown>");
System.err.printf(
"Rejected unparsed %s input from %s after %d attributed bytes%s%n",
unparsedRequest.getReason(),
remoteAddress,
unparsedRequest.getObservedByteCount(),
unparsedRequest.isCaptureTruncated() ? " (capture truncated)" : ""
);
}
}).build();
The built-in HTTP server dispatches this callback to its configured request-handler executor, never inline on a socket selector. The framework-managed default executor has bounded concurrency and queue capacity; a custom executor controls its own capacity. An observer exception is contained, and response marshaling still proceeds if timeout budget remains. The callback and marshaler share the server's requestHandlerTimeout budget, which bounds how long the transport waits and cooperatively interrupts the worker rather than forcibly terminating application code. During queue saturation Soklet immediately uses its built-in response instead, so this detailed callback is best-effort rather than a lossless audit stream; the rejection still reaches the existing low-cardinality transport-failure metric.
Raw Input Is Sensitive
UnparsedRequest::getCapturedBytes exposes up to 64 KiB of unparsed, unredacted input attributed through the parser-proven failure boundary for the built-in HTTP server. It may contain credentials, cookies, body fragments, control bytes, or binary data. Do not log or persist it without deliberate redaction and retention controls. Prefer the typed reason, attributed byte count, truncation flag, and optional remote address for routine telemetry. See Unparsed HTTP Requests for the complete contract.
References:
LifecycleObserver::willAcceptRequestLifecycleObserver::didAcceptRequestLifecycleObserver::didFailToAcceptRequestLifecycleObserver::willReadRequestLifecycleObserver::didReadRequestLifecycleObserver::didFailToReadRequestLifecycleObserver::didRejectUnparsedRequestUnparsedRequestUnparsedRequestReasonRequestReadFailureReasonRequestRejectionReason
Request Handling
These methods are fired at the very start of request processing and the very end, respectively.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void didStartRequestHandling(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod
) {
System.out.printf("Received request: %s\n", request);
// If there was no resourceMethod matching the request, expect a 404
if(resourceMethod != null)
System.out.printf("Request to be handled by: %s\n", resourceMethod);
else
System.out.println("This will be a 404.");
}
@Override
public void didFinishRequestHandling(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse,
@NonNull Duration processingDuration,
@NonNull List<Throwable> throwables
) {
// We have access to a few things here...
// * marshaledResponse is what was ultimately sent
// over the wire
// * processingDuration is how long everything took,
// including sending the response to the client
// * throwables is the ordered list of exceptions
// thrown during execution (if any)
long millis = processingDuration.toMillis();
System.out.printf("Entire request took %dms\n", millis);
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void didStartRequestHandling(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod
) {
System.out.printf("Received request: %s\n", request);
// If there was no resourceMethod matching the request, expect a 404
if(resourceMethod != null)
System.out.printf("Request to be handled by: %s\n", resourceMethod);
else
System.out.println("This will be a 404.");
}
@Override
public void didFinishRequestHandling(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse,
@NonNull Duration processingDuration,
@NonNull List<Throwable> throwables
) {
// We have access to a few things here...
// * marshaledResponse is what was ultimately sent
// over the wire
// * processingDuration is how long everything took,
// including sending the response to the client
// * throwables is the ordered list of exceptions
// thrown during execution (if any)
long millis = processingDuration.toMillis();
System.out.printf("Entire request took %dms\n", millis);
}
}).build();
References:
Response Writing
Monitor the response writing process - sending bytes over the wire. You can respond to successful writes or failed writes (e.g. unexpected client disconnect).
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willWriteResponse(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse
) {
// Access to marshaledResponse here lets us see exactly
// how much response body data will be written
Long bodyLength = marshaledResponse.getBodyLength();
System.out.printf("About to start writing response with " +
"a %d-byte body...\n", bodyLength);
}
@Override
public void didWriteResponse(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse,
@NonNull Duration responseWriteDuration
) {
long millis = responseWriteDuration.toMillis();
System.out.printf("Took %dms to write response\n", millis);
}
@Override
public void didFailToWriteResponse(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse,
@NonNull Duration responseWriteDuration,
@NonNull Throwable throwable
) {
long millis = responseWriteDuration.toMillis();
System.out.printf("Response write failed after %dms\n", millis);
// Use this to monitor trends in unexpected client disconnects
System.err.println("Exception occurred while writing response");
throwable.printStackTrace();
}
@Override
public void willTerminateResponseStream(
@NonNull StreamingResponseHandle streamingResponseHandle,
@NonNull StreamTermination streamTermination
) {
System.out.printf("Streaming response terminating: %s%n",
streamTermination.getReason());
}
@Override
public void didTerminateResponseStream(
@NonNull StreamingResponseHandle streamingResponseHandle,
@NonNull StreamTermination streamTermination
) {
if (streamTermination.getReason() == StreamTerminationReason.COMPLETED) {
System.out.println("Streaming response completed normally");
} else {
System.err.printf("Streaming response ended after %dms: %s%n",
streamTermination.getDuration().toMillis(), streamTermination.getReason());
}
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willWriteResponse(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse
) {
// Access to marshaledResponse here lets us see exactly
// how much response body data will be written
Long bodyLength = marshaledResponse.getBodyLength();
System.out.printf("About to start writing response with " +
"a %d-byte body...\n", bodyLength);
}
@Override
public void didWriteResponse(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse,
@NonNull Duration responseWriteDuration
) {
long millis = responseWriteDuration.toMillis();
System.out.printf("Took %dms to write response\n", millis);
}
@Override
public void didFailToWriteResponse(
@NonNull ServerType serverType,
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
@NonNull MarshaledResponse marshaledResponse,
@NonNull Duration responseWriteDuration,
@NonNull Throwable throwable
) {
long millis = responseWriteDuration.toMillis();
System.out.printf("Response write failed after %dms\n", millis);
// Use this to monitor trends in unexpected client disconnects
System.err.println("Exception occurred while writing response");
throwable.printStackTrace();
}
@Override
public void willTerminateResponseStream(
@NonNull StreamingResponseHandle streamingResponseHandle,
@NonNull StreamTermination streamTermination
) {
System.out.printf("Streaming response terminating: %s%n",
streamTermination.getReason());
}
@Override
public void didTerminateResponseStream(
@NonNull StreamingResponseHandle streamingResponseHandle,
@NonNull StreamTermination streamTermination
) {
if (streamTermination.getReason() == StreamTerminationReason.COMPLETED) {
System.out.println("Streaming response completed normally");
} else {
System.err.printf("Streaming response ended after %dms: %s%n",
streamTermination.getDuration().toMillis(), streamTermination.getReason());
}
}
}).build();
For non-streaming responses, didWriteResponse and didFailToWriteResponse cover the response write handoff. For StreamingResponseBody, willTerminateResponseStream and didTerminateResponseStream are invoked when the stream completes, is canceled, or fails. These hooks record stream duration and distinguish client disconnects from producer failures. Managed notification uses bounded callback dispatch. The terminal outcome does not prove that owned resources or other application work have physically finished cleanup; retained work remains accounted for until it exits. Keep observer callbacks prompt. Cleanup that exceeds its budget during otherwise normal finalization produces CLEANUP_TIMEOUT; an earlier terminal reason is preserved.
For request correlation, prefer the request-bearing objects already passed through the lifecycle API. StreamingResponseHandle and SseConnection expose their originating Request via StreamingResponseHandle::getRequest and SseConnection::getRequest. MCP lifecycle callbacks receive an McpRequestContext, whose getRequest() method exposes the physical request. LogEvent also exposes a request when one is available. Use Request::getId for local correlation. For distributed tracing and current MCP API references, see Trace Context and MCP.
References:
LifecycleObserver::willWriteResponseLifecycleObserver::didWriteResponseLifecycleObserver::didFailToWriteResponseLifecycleObserver::willTerminateResponseStreamLifecycleObserver::didTerminateResponseStream
Stream Termination
Soklet uses the same StreamTermination and StreamTerminationReason model for streaming HTTP responses and dedicated SSE connections. MCP request streams and subscriptions use the separate McpStreamTerminationReason vocabulary described in MCP.
| Reason | Common sources |
|---|---|
COMPLETED | Streaming HTTP response producer finished normally |
CLIENT_DISCONNECTED | HTTP streaming client or SSE client closed the connection |
SERVER_STOPPING | The owning server stopped while the stream was active |
PROTOCOL_UNSUPPORTED | A request protocol cannot support the stream, such as HTTP/1.0 for chunked streaming |
RESPONSE_TIMEOUT | Streaming HTTP response exceeded its total timeout |
RESPONSE_IDLE_TIMEOUT | Streaming HTTP response producer exceeded its idle timeout |
APPLICATION_CANCELED | Producer code intentionally threw StreamingResponseCanceledException |
BACKPRESSURE | SSE connection was closed because its write queue reached capacity |
WRITE_FAILED | Stream write or transport processing failed |
PRODUCER_FAILED | Streaming HTTP response producer threw unexpectedly |
INTERNAL_ERROR | Unexpected internal error |
SIMULATOR_LIMIT_EXCEEDED | The Simulator refused to materialize more streaming response bytes |
UNKNOWN | Stream ended and no more specific reason was available |
Server-Sent Events
If your application configures a SseServer, additional lifecycle hooks are available for SSE server and connection activity.
SSE Server Start/Stop
SokletConfig config = SokletConfig.withSseServer(
SseServer.fromPort(8081)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willStartSseServer(
@NonNull SseServer sseServer
) {
System.out.println("SSE server starting.");
}
@Override
public void didStartSseServer(
@NonNull SseServer sseServer
) {
System.out.println("SSE server started.");
}
@Override
public void didFailToStartSseServer(
@NonNull SseServer sseServer,
@NonNull Throwable throwable
) {
System.err.println("SSE server failed to start.");
throwable.printStackTrace();
}
@Override
public void willStopSseServer(
@NonNull SseServer sseServer
) {
System.out.println("SSE server stopping.");
}
@Override
public void didStopSseServer(
@NonNull SseServer sseServer,
@NonNull ShutdownComponentResult shutdownComponentResult
) {
System.out.printf("SSE server stopped: %s%n", shutdownComponentResult);
}
}).build();
SokletConfig config = SokletConfig.withSseServer(
SseServer.fromPort(8081)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willStartSseServer(
@NonNull SseServer sseServer
) {
System.out.println("SSE server starting.");
}
@Override
public void didStartSseServer(
@NonNull SseServer sseServer
) {
System.out.println("SSE server started.");
}
@Override
public void didFailToStartSseServer(
@NonNull SseServer sseServer,
@NonNull Throwable throwable
) {
System.err.println("SSE server failed to start.");
throwable.printStackTrace();
}
@Override
public void willStopSseServer(
@NonNull SseServer sseServer
) {
System.out.println("SSE server stopping.");
}
@Override
public void didStopSseServer(
@NonNull SseServer sseServer,
@NonNull ShutdownComponentResult shutdownComponentResult
) {
System.out.printf("SSE server stopped: %s%n", shutdownComponentResult);
}
}).build();
References:
LifecycleObserver::willStartSseServerLifecycleObserver::didStartSseServerLifecycleObserver::didFailToStartSseServerLifecycleObserver::willStopSseServerLifecycleObserver::didStopSseServer
SSE Connections
SokletConfig config = SokletConfig.withSseServer(
SseServer.fromPort(8081)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willEstablishSseConnection(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod
) {
System.out.printf("Establishing SSE connection for %s\n", request);
}
@Override
public void didEstablishSseConnection(
@NonNull SseConnection sseConnection
) {
System.out.printf("SSE connection established: %s\n", sseConnection);
}
@Override
public void didFailToEstablishSseConnection(
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
SseConnection.@NonNull HandshakeFailureReason connectionHandshakeFailureReason,
@Nullable Throwable throwable
) {
System.err.println("SSE connection establishment failed.");
if (throwable != null)
throwable.printStackTrace();
}
@Override
public void willTerminateSseConnection(
@NonNull SseConnection sseConnection,
@NonNull StreamTermination streamTermination
) {
System.out.printf("SSE connection terminating (%s)\n", streamTermination.getReason());
}
@Override
public void didTerminateSseConnection(
@NonNull SseConnection sseConnection,
@NonNull StreamTermination streamTermination
) {
System.out.printf("SSE connection terminated after %dms (%s)\n",
streamTermination.getDuration().toMillis(), streamTermination.getReason());
}
}).build();
SokletConfig config = SokletConfig.withSseServer(
SseServer.fromPort(8081)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willEstablishSseConnection(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod
) {
System.out.printf("Establishing SSE connection for %s\n", request);
}
@Override
public void didEstablishSseConnection(
@NonNull SseConnection sseConnection
) {
System.out.printf("SSE connection established: %s\n", sseConnection);
}
@Override
public void didFailToEstablishSseConnection(
@NonNull Request request,
@Nullable ResourceMethod resourceMethod,
SseConnection.@NonNull HandshakeFailureReason connectionHandshakeFailureReason,
@Nullable Throwable throwable
) {
System.err.println("SSE connection establishment failed.");
if (throwable != null)
throwable.printStackTrace();
}
@Override
public void willTerminateSseConnection(
@NonNull SseConnection sseConnection,
@NonNull StreamTermination streamTermination
) {
System.out.printf("SSE connection terminating (%s)\n", streamTermination.getReason());
}
@Override
public void didTerminateSseConnection(
@NonNull SseConnection sseConnection,
@NonNull StreamTermination streamTermination
) {
System.out.printf("SSE connection terminated after %dms (%s)\n",
streamTermination.getDuration().toMillis(), streamTermination.getReason());
}
}).build();
References:
LifecycleObserver::willEstablishSseConnectionLifecycleObserver::didEstablishSseConnectionLifecycleObserver::didFailToEstablishSseConnectionLifecycleObserver::willTerminateSseConnectionLifecycleObserver::didTerminateSseConnection
SSE Event and Comment Writes
SokletConfig config = SokletConfig.withSseServer(
SseServer.fromPort(8081)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willWriteSseEvent(
@NonNull SseConnection sseConnection,
@NonNull SseEvent sseEvent
) {
System.out.printf("Writing SSE event %s\n", sseEvent.getEvent().orElse("message"));
}
@Override
public void didWriteSseEvent(
@NonNull SseConnection sseConnection,
@NonNull SseEvent sseEvent,
@NonNull Duration writeDuration
) {
System.out.printf("SSE event write took %dms\n", writeDuration.toMillis());
}
@Override
public void didFailToWriteSseEvent(
@NonNull SseConnection sseConnection,
@NonNull SseEvent sseEvent,
@NonNull Duration writeDuration,
@NonNull Throwable throwable
) {
System.err.println("SSE event write failed.");
throwable.printStackTrace();
}
@Override
public void willWriteSseComment(
@NonNull SseConnection sseConnection,
@NonNull SseComment sseComment
) {
System.out.printf("Writing SSE comment (%s): %s\n",
sseComment.getCommentType(),
sseComment.getComment().orElse("<heartbeat>"));
}
@Override
public void didWriteSseComment(
@NonNull SseConnection sseConnection,
@NonNull SseComment sseComment,
@NonNull Duration writeDuration
) {
System.out.printf("SSE comment write took %dms\n", writeDuration.toMillis());
}
@Override
public void didFailToWriteSseComment(
@NonNull SseConnection sseConnection,
@NonNull SseComment sseComment,
@NonNull Duration writeDuration,
@NonNull Throwable throwable
) {
System.err.println("SSE comment write failed.");
throwable.printStackTrace();
}
}).build();
SokletConfig config = SokletConfig.withSseServer(
SseServer.fromPort(8081)
).lifecycleObserver(new LifecycleObserver() {
@Override
public void willWriteSseEvent(
@NonNull SseConnection sseConnection,
@NonNull SseEvent sseEvent
) {
System.out.printf("Writing SSE event %s\n", sseEvent.getEvent().orElse("message"));
}
@Override
public void didWriteSseEvent(
@NonNull SseConnection sseConnection,
@NonNull SseEvent sseEvent,
@NonNull Duration writeDuration
) {
System.out.printf("SSE event write took %dms\n", writeDuration.toMillis());
}
@Override
public void didFailToWriteSseEvent(
@NonNull SseConnection sseConnection,
@NonNull SseEvent sseEvent,
@NonNull Duration writeDuration,
@NonNull Throwable throwable
) {
System.err.println("SSE event write failed.");
throwable.printStackTrace();
}
@Override
public void willWriteSseComment(
@NonNull SseConnection sseConnection,
@NonNull SseComment sseComment
) {
System.out.printf("Writing SSE comment (%s): %s\n",
sseComment.getCommentType(),
sseComment.getComment().orElse("<heartbeat>"));
}
@Override
public void didWriteSseComment(
@NonNull SseConnection sseConnection,
@NonNull SseComment sseComment,
@NonNull Duration writeDuration
) {
System.out.printf("SSE comment write took %dms\n", writeDuration.toMillis());
}
@Override
public void didFailToWriteSseComment(
@NonNull SseConnection sseConnection,
@NonNull SseComment sseComment,
@NonNull Duration writeDuration,
@NonNull Throwable throwable
) {
System.err.println("SSE comment write failed.");
throwable.printStackTrace();
}
}).build();
References:
LifecycleObserver::willWriteSseEventLifecycleObserver::didWriteSseEventLifecycleObserver::didFailToWriteSseEventLifecycleObserver::willWriteSseCommentLifecycleObserver::didWriteSseCommentLifecycleObserver::didFailToWriteSseComment
Model Context Protocol
Soklet's 2026-07-28 MCP path is stateless. The explicitly selected 2025-06-18 and 2025-11-25 path accepts initialize and remains session-disabled by default. Explicit session configuration adds remembered public client metadata and active-request cancelation. It adds session-bound GET notification delivery, DELETE and authorized resource subscriptions, with no public session lifecycle callbacks. LifecycleObserver instead exposes MCP server start/stop hooks and one admitted-request lifecycle. The same immutable McpRequestContext instance is supplied when handling starts and when the request reaches its client-visible terminal outcome, including request-scoped SSE and subscription outcomes on 2026-07-28.
// The application owns a bounded, nonblocking observation queue.
// A separate worker drains it; offer() returns immediately when full.
LifecycleObserver observer = new LifecycleObserver() {
@Override
public void didStartMcpRequestHandling(
@NonNull McpRequestContext requestContext
) {
observationQueue.offer("Starting MCP " + requestContext.getJsonRpcMethod());
}
@Override
public void didFinishMcpRequestHandling(
@NonNull McpRequestContext requestContext,
@NonNull McpRequestOutcome requestOutcome,
@Nullable McpJsonRpcError jsonRpcError,
@NonNull Duration requestDuration,
@NonNull List<@NonNull Throwable> throwables
) {
observationQueue.offer("Finished MCP " + requestContext.getJsonRpcMethod()
+ " with " + requestOutcome + " in " + requestDuration.toMillis() + "ms");
}
@Override
public void didStopMcpServer(
@NonNull McpServer mcpServer,
@NonNull ShutdownComponentResult shutdownComponentResult
) {
System.out.printf("MCP server stopped: %s%n",
shutdownComponentResult.getShutdownComponentDisposition());
}
};
// The application owns a bounded, nonblocking observation queue.
// A separate worker drains it; offer() returns immediately when full.
LifecycleObserver observer = new LifecycleObserver() {
@Override
public void didStartMcpRequestHandling(
@NonNull McpRequestContext requestContext
) {
observationQueue.offer("Starting MCP " + requestContext.getJsonRpcMethod());
}
@Override
public void didFinishMcpRequestHandling(
@NonNull McpRequestContext requestContext,
@NonNull McpRequestOutcome requestOutcome,
@Nullable McpJsonRpcError jsonRpcError,
@NonNull Duration requestDuration,
@NonNull List<@NonNull Throwable> throwables
) {
observationQueue.offer("Finished MCP " + requestContext.getJsonRpcMethod()
+ " with " + requestOutcome + " in " + requestDuration.toMillis() + "ms");
}
@Override
public void didStopMcpServer(
@NonNull McpServer mcpServer,
@NonNull ShutdownComponentResult shutdownComponentResult
) {
System.out.printf("MCP server stopped: %s%n",
shutdownComponentResult.getShutdownComponentDisposition());
}
};
Start observation shares the separately configured MCP protocol pool with admission, CORS, both rate limiters and request-state opening. Use protocolExecutorConcurrency and protocolExecutorQueueCapacity to change its 32-worker/128-queue defaults; handler executor settings do not resize it. Finish observation and its trace/failure logs use a separate bounded dispatcher with delivery reserved before start. They do not run on the connection event loop. A blocked observer still retains physical shutdown work; keep operations finite and do not wait for the same Soklet lifecycle to finish from a callback.
The start callback runs after structural validation and admission. The finish callback is captured exactly once for every admitted request or notification and delivered by the observation worker; it describes the client-visible request finish, not proof that non-cooperative application code has exited. See MCP for request outcomes, tracing privacy, stream/subscription lifetimes, and shutdown semantics.
References:
See MCP for the current LifecycleObserver::didStartMcpRequestHandling, LifecycleObserver::didFinishMcpRequestHandling, and LifecycleObserver::didStopMcpServer signatures, plus the McpRequestContext, McpRequestOutcome, and shared ShutdownComponentResult contracts.
Event Logging
Soklet provides insight into unexpected errors that occur during internal processing that are not otherwise surfaced via LogEvent objects provided to LifecycleObserver::didReceiveLogEvent.
For example, you might want to specially monitor scenarios in which your ResponseMarshaler::forThrowable failed (that is, you attempted to write an error response for an exception that bubbled out, but that attempt threw an exception, forcing Soklet to write its own failsafe response) - you could do this by observing events with type LogEventType.RESPONSE_MARSHALER_FOR_THROWABLE_FAILED. Low-level HTTP, SSE, and MCP transport failures can emit LogEventType.SERVER_TRANSPORT_FAILURE. MCP accept-loop failures are recorded through MetricsCollector.didRecordMcpMetricsEvent as a McpMetricsEvent.TransportFailure with reason ACCEPT_LOOP_ERROR; they do not also emit this log event.
Built-in MCP request-observer, semantic-metrics collector and transport failure events deliberately omit Throwable, Request, ResourceMethod and MarshaledResponse attachments, along with exception text and stack traces. HTTP/SSE failure events may attach the original Throwable. Typed application callbacks and aggregate lifecycle-transition observer failures have separate retention contracts; see MCP Failure Log Events And Redaction.
The LifecycleObserver::didReceiveLogEvent interface default is a no-op. LifecycleObserver.defaultInstance() writes event messages and attached Throwable stack traces to stderr; Soklet selects it when no observer configuration is supplied. Configuring a custom observer or collection replaces that default. Route logs by overriding the callback, as below, or include the default instance explicitly if you want stderr output alongside other observers. Tracing-only observers, including OpenTelemetry, do not print an implicit copy of each event. Null/empty observer configuration is silent.
The default stderr observer prints routine executor shedding, request interruption and transport socket-close/timeout events as single lines with the exception class, avoiding full stack rendering during overload or normal cancelation. Unexpected failures, including nested or suppressed diagnostics, retain their stacks. Custom log observers continue to receive the exact original event and Throwable and can choose their own policy.
Soklet finalization also has a separate bounded terminal stderr report, which bypasses this log-event channel.
Your LifecycleObserver can listen for LogEvent values like this:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
// This example uses SLF4J. See https://www.slf4j.org
private final Logger logger =
LoggerFactory.getLogger("com.soklet.example.LifecycleObserver");
@Override
public void didReceiveLogEvent(@NonNull LogEvent logEvent) {
// These properties are available in LogEvent
LogEventType logEventType = logEvent.getLogEventType();
String message = logEvent.getMessage();
Optional<Throwable> throwable = logEvent.getThrowable();
Optional<Request> request = logEvent.getRequest();
Optional<ResourceMethod> resourceMethod = logEvent.getResourceMethod();
Optional<MarshaledResponse> marshaledResponse = logEvent.getMarshaledResponse();
// Log the message however you like
logger.warn(message, throwable.orElse(null));
}
}).build();
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).lifecycleObserver(new LifecycleObserver() {
// This example uses SLF4J. See https://www.slf4j.org
private final Logger logger =
LoggerFactory.getLogger("com.soklet.example.LifecycleObserver");
@Override
public void didReceiveLogEvent(@NonNull LogEvent logEvent) {
// These properties are available in LogEvent
LogEventType logEventType = logEvent.getLogEventType();
String message = logEvent.getMessage();
Optional<Throwable> throwable = logEvent.getThrowable();
Optional<Request> request = logEvent.getRequest();
Optional<ResourceMethod> resourceMethod = logEvent.getResourceMethod();
Optional<MarshaledResponse> marshaledResponse = logEvent.getMarshaledResponse();
// Log the message however you like
logger.warn(message, throwable.orElse(null));
}
}).build();
References:
Custom HTTP streaming completion
Custom transports that guarantee a stream termination callback call LifecycleObserver.willWriteResponseStream and MetricsCollector.willWriteResponseStream before request-handling finish. Preparation and termination use the same handle and original dispatched request identity. Termination can arrive before handling finish; observers must handle either order without blocking. Without preparation, default request accounting and OTel spans end at handoff. Transport decorators must forward preparation and termination together.

