oat-sa / lib-correlation-ids-guzzle
OAT Correlation Ids Guzzle Library
Installs: 6 007
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 45
Forks: 0
Open Issues: 0
Requires
- php: ^7.1.3 || ^8.0
- guzzlehttp/guzzle: ^6.4|^7.0
- oat-sa/lib-correlation-ids: ^0.2.0
Requires (Dev)
- phpunit/phpunit: ^8.3
This package is auto-updated.
Last update: 2024-11-02 10:41:53 UTC
README
PHP library for correlation ids guzzle middleware based on the correlation ids library.
Table of contents
Installation
$ composer require oat-sa/lib-correlation-ids-guzzle
Principles
This library provides a ready to use guzzle middleware that forwards, as request headers, the correlation ids fetched from the correlation ids registry.
Notes
- the current process correlation id will be forwarded as the parent one,
- the root correlation id will be also forwarded.
More details about calls chaining available on the correlation ids library documentation.
Usage
With the provided factory
The GuzzleClientFactory
creates for you a guzzle client with the middleware already enabled:
<?php declare(strict_types=1); use OAT\Library\CorrelationIds\Registry\CorrelationIdsRegistry; use OAT\Library\CorrelationIds\Registry\CorrelationIdsRegistryInterface; use OAT\Library\CorrelationIdsGuzzle\Factory\GuzzleClientFactory; use OAT\Library\CorrelationIdsGuzzle\Middleware\CorrelationIdsGuzzleMiddleware; /** @var CorrelationIdsRegistryInterface $registry */ $registry = new CorrelationIdsRegistry(...); $clientFactory = new GuzzleClientFactory(new CorrelationIdsGuzzleMiddleware($registry))); $client = $clientFactory->create(['some' => 'options']); ... $client->request('GET', 'http://example.com'); // Will forward correlation ids as request headers automatically.
Manually
You need to push the CorrelationIdsGuzzleMiddleware
to your handler stack as follow:
<?php declare(strict_types=1); use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use OAT\Library\CorrelationIds\Registry\CorrelationIdsRegistry; use OAT\Library\CorrelationIds\Registry\CorrelationIdsRegistryInterface; use OAT\Library\CorrelationIdsGuzzle\Middleware\CorrelationIdsGuzzleMiddleware; /** @var CorrelationIdsRegistryInterface $registry */ $registry = new CorrelationIdsRegistry(...); $handlerStack = HandlerStack::create(); $handlerStack->push(Middleware::mapRequest(new CorrelationIdsGuzzleMiddleware($registry))); $client = new Client(['handler' => $handlerStack]); ... $client->request('GET', 'http://example.com'); // Will forward correlation ids as request headers automatically.
Note: you can customize the log context key names by providing you own CorrelationIdsHeaderNamesProviderInterface implementation and pass it to the CorrelationIdsGuzzleMiddleware
constructor.
Tests
To run tests:
$ vendor/bin/phpunit
Note: see phpunit.xml.dist for available test suites.