bilfeldt/laravel-correlation-id
Composer 安装命令:
composer require bilfeldt/laravel-correlation-id
包简介
Deal with Request-ID and Correlation-ID in Laravel applications
README 文档
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.
| Version | Laravel | PHP |
|---|---|---|
| 1.* | 10.* | 11.* | 12.* | 8.1.* | 8.2.* | 8.3.* | 8.4.* |
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 (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.
Laravel 11
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); })
Laravel 10 and below
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, ];
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.
bilfeldt/laravel-correlation-id 适用场景与选型建议
bilfeldt/laravel-correlation-id 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 132.02k 次下载、GitHub Stars 达 8, 最近一次更新时间为 2023 年 09 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「request id」 「correlation id」 「bilfeldt」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 bilfeldt/laravel-correlation-id 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 bilfeldt/laravel-correlation-id 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 bilfeldt/laravel-correlation-id 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A logger for the Laravel HTTP Client
Log Laravel application request and responses for debugging or statistics
Log statistics about route usage per user/team
Flash multiple messages using Laravels default session message flashing system
Библиотека для отслеживание запроса между сервисами
Include a correlation identifier in all requests.
统计信息
- 总下载量: 132.02k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 8
- 点击次数: 31
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-09-26
