bilfeldt / laravel-correlation-id
Deal with Request-ID and Correlation-ID in Laravel applications
Fund package maintenance!
bilfeldt
Installs: 34 045
Dependents: 1
Suggesters: 0
Security: 0
Stars: 4
Watchers: 1
Forks: 0
Open Issues: 2
Requires
- php: ~8.1.0 || ~8.2.0 || ~8.3.0
- illuminate/contracts: ^10.0 || ^11.0
Requires (Dev)
- nunomaduro/collision: ^7.8 || ^8.0
- orchestra/testbench: ^8.0 || ^9.0
- phpunit/phpunit: ^10.0
README
Create request Correlation-IDs via middleware and pass both this globally unique Correlation-ID
and any user provided Request-ID
to the global log context.
Motivation
Each and every request should have a unique Correlation ID which uniquely determines the user interaction. This Correlation ID should then be added to all log entries as context, to error reporting and to any subsystem like external API calls or queued jobs. Doing so, makes is possible to track relevant touch points for a given user request. Read more here.
A client can also provide a Request ID which it is good practice to return again in the response and correlate to the Correlation ID. Read more here.
Installation
You can install the package via composer:
composer require bilfeldt/laravel-correlation-id
Assigning Correlation ID to requests
Note
Ideally, the unique Correlation ID should be created at the very first touch point of your infrastructure like the initial server which could be a load balancer
As it can be tricky to create Correlation ID on the server level and this is so easy in Laravel using middleware. This package provides a middleware for creating a Correlation ID and attaching it to the request as a header Correlation-ID
and to the response header as well. You should either assign the correlation id on the first touch point of your infrastructure or register the CorrelationIdMiddleware
middleware globally as the first middleware in the $middleware
property of your app/Http/Kernel.php
class:
// app/Http/Kernel.php /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array<int, class-string|string> */ protected $middleware = [ \Bilfeldt\CorrelationId\Middleware\CorrelationIdMiddleware::class, // <!-- Add this globally as the first toutchpoint // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Illuminate\Http\Middleware\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ];
Assigning Request ID to responses
If the client provides a Request ID in the request header, then it is good practice to copy that to the response header. This is done by adding the ClientRequestIdMiddleware
middleware globally in the $middleware
property of your app/Http/Kernel.php
class:
// app/Http/Kernel.php /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array<int, class-string|string> */ protected $middleware = [ \Bilfeldt\CorrelationId\Middleware\CorrelationIdMiddleware::class, \Bilfeldt\CorrelationId\Middleware\ClientRequestIdMiddleware::class, // <!-- Add this globally // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Illuminate\Http\Middleware\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ];
Usage
This package registers a few macros on the Illuminate\Http\Request
class:
$request->getCorrelationId(); // UUID or null if not assigned $request->getClientRequestId(); // The `Request-ID` header if provided by the client $request->getUniqueId(); // Unique UUID for each request: 94d0e2d6-4cc6-449c-9140-80bca47d29b4
Add global log context
It is possible to add both the Correlation ID and the Request ID to the global log context so that any writing to logs once those are added will automatically have the id's attached as context.
It is recommended to add them to the logging context just after assigning them to the request. This can be done by globally registering the middleware LogContextMiddleware
in the $middleware
property of your app/Http/Kernel.php
class:
// app/Http/Kernel.php /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array<int, class-string|string> */ protected $middleware = [ \Bilfeldt\CorrelationId\Middleware\CorrelationIdMiddleware::class, \Bilfeldt\CorrelationId\Middleware\ClientRequestIdMiddleware::class, \Bilfeldt\CorrelationId\Middleware\LogContextMiddleware::class, // <!-- Add this globally AFTER assigning Correlation ID and Request ID. // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Illuminate\Http\Middleware\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ];
Add global context to error reporting
It is possible to add both the Correlation ID and the Request ID to the global error reporting context so that any error reporting once those are added will automatically have the id's attached as context.
If the variables have already been added to the log context, then I recommend merging all the global log context to the error reporting context overriding the context
method of your application's App\Exceptions\Handler
:
// app/Exceptions/Handler.php /** * Get the default context variables for logging. * * @return array<string, mixed> */ protected function context(): array { return array_merge(parent::context(), $this->getGlobalLogContext()); } private function getGlobalLogContext(): array { try { return Log::sharedContext(); } catch (\Throwable $e) { return []; } }
Alternatively if you do not want to share all the global log context, simply fetch the IDs from the request()
helper using the macros described above:
// app/Exceptions/Handler.php /** * Get the default context variables for logging. * * @return array<string, mixed> */ protected function context(): array { return array_merge(parent::context(), [ 'correlation_id' => request()->getCorrelationId(), 'request_id' => request()->getUniqueId(), ]); }
Passing Correlation ID and Request ID to queued jobs
This package make sure that the Correlation ID and the Request ID are passed to the payload of queued jobs which can be retreived again using $job->payload()['data']
.
Just before a queued job is being processed, then we extract the Correlation ID and the Request ID from the payload and sets those on the Illuminate\Http\Request
instance, so that any subsequent jobs that could get dispatched will also have them attached.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- Anders Bilfeldt
- James Brooks: For his blog post on how to inject additional data into Laravel queued jobs.
- All Contributors
License
The MIT License (MIT). Please see License File for more information.