77* [ How to use] ( #how-to-use )
88 + [ Wiring the middleware] ( #wiring-the-middleware )
99 + [ Configuring a custom provider] ( #configuring-a-custom-provider )
10+ + [ Propagating to outbound boundaries] ( #propagating-to-outbound-boundaries )
1011 + [ Emitting correlated logs] ( #emitting-correlated-logs )
12+ * [ Concurrency model] ( #concurrency-model )
1113* [ License] ( #license )
1214* [ Contributing] ( #contributing )
1315
1618Provides a PSR-15 middleware that guarantees every inbound HTTP request carries a correlation identifier. When the
1719incoming request already includes a ` Correlation-Id ` header, the value is reused. Otherwise, a new identifier is
1820generated through a configurable provider (UUID v7 by default). The correlation ID is exposed as the request
19- attribute ` correlationId ` so downstream handlers can read it, and is echoed back through the ` Correlation-Id `
20- response header for end-to-end tracing across services.
21+ attribute ` correlationId ` , is available through ` CorrelationIdMiddleware::correlationId() ` for outbound
22+ propagation, and is echoed back through the ` Correlation-Id ` response header for end-to-end tracing across
23+ services.
2124
22- The library also ships ` CorrelatedLogger ` , a thin wrapper over any PSR-3 ` LoggerInterface ` that resolves the
23- correlation ID from the request and attaches it to the log context under the ` correlation_id ` key. This produces
24- structured logs that can be grouped and filtered by the correlation ID without any extra plumbing in the consumer's
25- log calls.
25+ The library also ships ` CorrelatedLogger ` , a PSR-3 ` LoggerInterface ` decorator that reads the correlation ID at
26+ each log write and attaches it to the log context under the ` correlation_id ` key. This produces structured logs
27+ that can be grouped and filtered by the correlation ID without any extra plumbing in the consumer's log calls.
2628
2729## Installation
2830
@@ -49,7 +51,7 @@ use Psr\Http\Server\RequestHandlerInterface;
4951use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
5052
5153# Build the middleware with the default UUID v7 provider.
52- $middleware = CorrelationIdMiddleware::create()-> build();
54+ $middleware = CorrelationIdMiddleware::build();
5355
5456# Process an inbound request through the middleware.
5557$response = $middleware->process(
@@ -93,45 +95,63 @@ $provider = new readonly class () implements CorrelationIdProvider {
9395};
9496
9597# Build the middleware with the custom provider.
96- $middleware = CorrelationIdMiddleware::create()
97- ->withProvider(provider: $provider)
98- ->build();
98+ $middleware = CorrelationIdMiddleware::build(provider: $provider);
99+ ```
100+
101+ ### Propagating to outbound boundaries
102+
103+ ` CorrelationIdMiddleware::correlationId() ` returns the correlation ID of the request in flight. The instance is
104+ stable, so it can be injected once into outbound boundaries (HTTP clients, message payloads), and its ` toString() `
105+ reflects, at read time, the identifier the middleware resolved for the request being handled. It reads as an
106+ empty string before any request was handled.
107+
108+ ``` php
109+ <?php
110+
111+ declare(strict_types=1);
112+
113+ use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
114+
115+ $middleware = CorrelationIdMiddleware::build();
116+
117+ # Inject into outbound clients, message publishers, or bind in the DI container.
118+ $correlationId = $middleware->correlationId();
119+
120+ # Anywhere downstream, while a request is being handled.
121+ $correlationId->toString();
99122```
100123
101124### Emitting correlated logs
102125
103- Uses ` CorrelatedLogger ` inside a downstream handler so that every log entry automatically carries the request's
104- correlation ID under the ` correlation_id ` context key.
126+ Decorates any PSR-3 logger once, at wiring time, with the correlation ID of the request in flight. Every log entry
127+ emitted anywhere in the application automatically carries the ` correlation_id ` context key, and entries emitted
128+ outside a request (boot, workers) simply omit the key.
105129
106130``` php
107131<?php
108132
109133declare(strict_types=1);
110134
111- use Psr\Http\Message\ResponseInterface;
112- use Psr\Http\Message\ServerRequestInterface;
113- use Psr\Http\Server\RequestHandlerInterface;
114- use Psr\Log\LoggerInterface;
115135use TinyBlocks\Http\CorrelationId\CorrelatedLogger;
136+ use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
116137
117- final readonly class PlaceOrderHandler implements RequestHandlerInterface
118- {
119- public function __construct(private LoggerInterface $logger)
120- {
121- }
122-
123- public function handle(ServerRequestInterface $request): ResponseInterface
124- {
125- # Resolve a PSR-3 logger that attaches the request's correlation ID to every log context.
126- $logger = CorrelatedLogger::from($this->logger)->resolve($request);
138+ $middleware = CorrelationIdMiddleware::build();
127139
128- $logger->info('Order placed.', ['order_id' => 42]);
140+ # Decorate the application logger once, at wiring time.
141+ $logger = CorrelatedLogger::from(logger: $applicationLogger, correlationId: $middleware->correlationId());
129142
130- # ...
131- }
132- }
143+ # Anywhere downstream, the entry carries the correlation_id context key.
144+ $logger->info('Order placed.', ['order_id' => 42]);
133145```
134146
147+ ## Concurrency model
148+
149+ ` correlationId() ` holds one value per middleware instance, which means one value per PHP process. This is correct
150+ on process-per-request runtimes (PHP-FPM, Apache mod_php), where a process handles a single request at a time. On
151+ long-running concurrent runtimes handling several requests in one process (Swoole, RoadRunner worker mode), use
152+ the request attribute ` correlationId ` (name available as ` CorrelationIdMiddleware::ATTRIBUTE_NAME ` ), which is
153+ isolated per request by construction.
154+
135155## License
136156
137157Http Correlation Id is licensed under [ MIT] ( LICENSE ) .
0 commit comments