Laravel Correlation ID Middleware
A package to manage correlation IDs for request tracing in Laravel applications.
A correlation ID is a unique identifier assigned to each request entering a distributed system. It helps developers trace requests, debug issues, and identify potential security threats. By attaching a correlation ID to each request, you can track its journey through various services and components, simplifying troubleshooting and monitoring.
? Installation
composer require mohamedahmed01/laravel-correlation
?? Configuration
Publish the Config File
php artisan vendor:publish --tag=correlation-config
Config Options (config/correlation.php
)
-
header
: Header name to use (default: `X-Correlation-ID`)
-
alternate_headers
: Additional headers to check for a correlation ID (e.g., `X-Request-ID`, `Trace-ID`)
-
generator
: Strategy for generating correlation IDs (`uuid`, `timestamp`, `hash`)
-
storage
: Store correlation IDs in `cache`, `session`, or `none`
-
queue
: Enable correlation ID propagation in queued jobs (default: `true`)
-
propagate
: Automatically include correlation ID in outgoing HTTP requests (default: `true`)
-
auto_register_middleware
: Automatically register middleware (default: `true`)
? Usage
The correlation ID will be:
-
Extracted from incoming requests (from configured headers)
-
Generated if missing (based on configured strategy)
-
Stored in cache (if enabled)
-
Included in all responses
-
Available in logs
-
Passed through queued jobs
-
Propagated in HTTP requests
-
Accessible via helper functions and Blade directives
Middleware Registration
If auto_register_middleware
is disabled, manually register the middleware in app/Http/Kernel.php
:
protected $middleware = [
\Mohamedahmed01\LaravelCorrelation\Http\Middleware\CorrelationMiddleware::class,
];
Accessing the Correlation ID
? In Controllers or Services
$correlationId = correlation_id();
? In Blade Views
@correlationId
? In Jobs (Queued Work)
public function handle()
{
$correlationId = correlation_id();
Log::info("Processing job", ['correlation_id' => $correlationId]);
}
? In Logs
All logs during a request will automatically include the correlation ID:
{
"message": "User created",
"context": {
"correlation_id": "123e4567-e89b-12d3-a456-426614174000"
}
}
? HTTP Client Propagation
If propagate
is enabled, correlation IDs will be automatically included in outgoing HTTP requests:
$response = Http::withCorrelationId()->get('https://api.example.com/data');
? Artisan Commands
List stored correlation IDs:
php artisan correlation:list
? Testing
Run the test suite to ensure functionality:
php artisan test
? License
MIT License