PSR-7 Request ID middleware
This middleware provide framework-agnostic possibility to generate and add to request/response's header Request ID (Correlation ID).
composer require php-middleware/request-id
This middleware require in contructor PhpMiddleware\RequestId\RequestIdProviderFactoryInterface
implementation which
must create a new RequestIdProviderInterface
object. We provide RequestIdProvider
default implementation.
$generator = new PhpMiddleware\RequestId\Generator\PhpUniqidGenerator();
$requestIdProvider = new PhpMiddleware\RequestId\RequestIdProviderFactory($generator);
$requestIdMiddleware = new PhpMiddleware\RequestId\RequestIdMiddleware($requestIdProvider);
$app = new MiddlewareRunner();
$app->add($requestIdMiddleware);
$app->run($request, $response);
All Provider factory constructor options:
PhpMiddleware\RequestId\Generator\GeneratorInterface
$generator
- generator implementation (required)bool|PhpMiddleware\RequestId\OverridePolicy\OverridePolicyInterface
$allowOverride
(defaulttrue
) - iftrue
and request id header exists in incoming request, then value from request header will be used in middleware, using generator will be avoidstring
$requestHeader
(defaultX-Request-Id
) - request header name
How to get request id in my application?
- Middleware implements
RequestIdProviderInterface
, so you are able to usegetRequestId()
method, - from
request-id
attribute inServerRequest
object ($request->getAttribute(RequestIdMiddleware::ATTRIBUTE_NAME)
).
You can add your own logic to decide when override incoming request id. You can implement OverridePolicyInterface
and pass it as $allowOverride
variable in constructor.
We provide simple Monolog processor to add request it to every log entry!
RequestDecorator adds header with request id to your request object. It's useful when your microservices communicate between using PSR-7 HTTP messages e.g. Guzzle.
To generate request id you need to use implementation of PhpMiddleware\RequestId\Generator\GeneratorInterface
. There are predefined generators in PhpMiddleware\RequestId\Generator\
namespace:
Simple generator using uniqid function.
UUID1 implementations of Ramsey\Uuid. To use it you need to add ramsey/uuid
dependency to your composer.json
.
UUID3 implementations of Ramsey\Uuid. To use it you need to add ramsey/uuid
dependency to your composer.json
.
UUID4 implementations of Ramsey\Uuid. To use it you need to add ramsey/uuid
dependency to your composer.json
.
Generates Uuid4 like RamseyUuid4Generator
however it's not require any dependency (it use static factory method).
UUID5 implementations of Ramsey\Uuid. To use it you need to add ramsey/uuid
dependency to your composer.json
.
It adds prefix to generated request id.
This generator converts generated request id to md5 hash.
Middleware tested on:
Middleware should works with:
And any other modern framework supported middlewares and PSR-7.