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.
Version | Laravel | PHP |
---|---|---|
1.* | 10.* | 11.* | 8.1.* | 8.2.* | 8.3.* | 8.4.* |
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.
You can install the package via composer:
composer require bilfeldt/laravel-correlation-id
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 (I do accept a PR with suggestions on how to do this in Nginx 😃) 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 assign the correlation id using a global middleware pushed as the first middleware to be applied.
Registering a global middleware in Laravel 11 is done in the bootstrap/app.php
file:
// bootstrap/app.php
use App\Http\Middleware\EnsureTokenIsValid;
use Bilfeldt\CorrelationId\Middleware\CorrelationIdMiddleware
->withMiddleware(function (Middleware $middleware) {
$middleware->prepend(CorrelationIdMiddleware::class);
})
In Laravel 10 and below then a global middleware is added in the $middleware
property in app/Http/Kernel.php
:
// 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,
];
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,
];
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
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,
];
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(),
]);
}
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.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
- Anders Bilfeldt
- James Brooks: For his blog post on how to inject additional data into Laravel queued jobs.
- All Contributors
The MIT License (MIT). Please see License File for more information.