philiprehberger/laravel-correlation-id 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/laravel-correlation-id

Composer 安装命令:

composer require philiprehberger/laravel-correlation-id

包简介

Laravel middleware that generates or propagates correlation IDs for request tracing with automatic log context injection

README 文档

README

Tests Latest Version on Packagist Last updated

Laravel middleware that generates or propagates correlation IDs for request tracing with automatic log context injection.

Requirements

  • PHP 8.2+
  • Laravel 11 or 12

Installation

composer require philiprehberger/laravel-correlation-id

The service provider is registered automatically via Laravel package auto-discovery.

Optionally publish the config:

php artisan vendor:publish --tag=correlation-id-config

Usage

use PhilipRehberger\CorrelationId\AddCorrelationId;

// Register the middleware in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->prepend(AddCorrelationId::class);
})

Accessing the Correlation ID

use PhilipRehberger\CorrelationId\CorrelationId;

// Via the helper class
$id = CorrelationId::get();
CorrelationId::set('my-custom-id');

// Via the request macro
$id = $request->correlationId();

Configuration

// config/correlation-id.php
return [
    'request_headers' => ['X-Request-Id', 'X-Correlation-ID'],
    'response_header' => 'X-Request-Id',
    'log_context_key' => 'correlation_id',
    'sentry'          => true,
    'generator'       => 'uuid',
];

How It Works

  1. The middleware inspects incoming request headers in the order defined by request_headers.
  2. The first non-empty value found is used as-is (propagation path).
  3. When no matching header is present, a new ID is generated using the configured generator.
  4. The ID is stored as a request attribute and shared with the log context.
  5. After the handler returns, the ID is written to the response header defined by response_header.

Custom ID Generator

Control how new correlation IDs are generated when no upstream header is present:

// config/correlation-id.php

// UUID v4 (default)
'generator' => 'uuid',

// UUID v7 (time-ordered, sortable)
'generator' => 'uuid7',

// ULID (compact, sortable)
'generator' => 'ulid',

// Custom callable
'generator' => fn () => 'prefix-' . bin2hex(random_bytes(16)),

Queue Job Propagation

Propagate the correlation ID from the dispatching context into queued jobs:

use PhilipRehberger\CorrelationId\Concerns\TracksCorrelationId;
use PhilipRehberger\CorrelationId\Middleware\CorrelationIdJobMiddleware;

class ProcessOrder implements ShouldQueue
{
    use TracksCorrelationId;

    public function middleware(): array
    {
        return [new CorrelationIdJobMiddleware];
    }

    public function handle(): void
    {
        // CorrelationId::get() returns the same ID from dispatch time
    }
}

The TracksCorrelationId trait captures the current correlation ID when the job is created. The CorrelationIdJobMiddleware restores it when the job runs on a worker.

HTTP Client Propagation

Automatically forward the correlation ID to outgoing HTTP requests made with Laravel's HTTP client:

use Illuminate\Support\Facades\Http;
use PhilipRehberger\CorrelationId\CorrelationId;

$response = Http::withMiddleware(CorrelationId::httpMiddleware())
    ->get('https://api.example.com/orders');

// Uses a custom header name
$response = Http::withMiddleware(CorrelationId::httpMiddleware('X-Request-Id'))
    ->get('https://api.example.com/orders');

The middleware adds the X-Correlation-ID header (or your custom header) to every outgoing request.

Trace Spans

Track the timing of operations within a request using lightweight trace spans:

use PhilipRehberger\CorrelationId\CorrelationId;

$span = CorrelationId::startSpan('external-api-call', ['url' => $url]);

$response = Http::get($url);

$ended = CorrelationId::endSpan($span);

// Access span data
$ended->durationMs();  // Duration in milliseconds
$ended->toArray();     // Full array representation

// Retrieve all completed spans
$spans = CorrelationId::spans();

// Clear spans (e.g., between tests)
CorrelationId::clearSpans();

Spans are immutable value objects. Calling endSpan() returns a new instance with the end time set and stores it for later retrieval.

Sentry Integration

When sentry/sentry-laravel is installed and 'sentry' => true, the middleware sets correlation_id as a tag on every Sentry event captured during the request.

API

Class / Method Description
AddCorrelationId middleware Generates or propagates the correlation ID and injects it into logs and responses
CorrelationId::get() Read the current correlation ID (null if not yet set)
CorrelationId::set(string $id) Override the correlation ID (useful in tests or CLI commands)
CorrelationId::generate() Generate a new correlation ID using the configured generator
CorrelationId::reset() Clear the correlation ID and all trace spans for the current request
CorrelationId::httpMiddleware(?string $headerName) Returns a Guzzle middleware closure for HTTP client propagation
CorrelationId::startSpan(string $name, array $metadata) Start a new trace span linked to the current correlation ID
CorrelationId::endSpan(Span $span) End a span and store it for retrieval
CorrelationId::spans() Get all completed trace spans
CorrelationId::clearSpans() Clear all stored trace spans
$request->correlationId() Request macro that returns the current correlation ID
TracksCorrelationId trait Captures the correlation ID at dispatch time for queue jobs
CorrelationIdJobMiddleware Queue job middleware that restores the correlation ID
PropagateCorrelationId::handler() Static factory for the HTTP client propagation middleware
Span value object Immutable span with name, durationMs(), toArray()

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/laravel-correlation-id 适用场景与选型建议

philiprehberger/laravel-correlation-id 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 77 次下载、GitHub Stars 达 2, 最近一次更新时间为 2026 年 03 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「logging」 「middleware」 「laravel」 「request-id」 「correlation-id」 「tracing」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/laravel-correlation-id 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/laravel-correlation-id 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/laravel-correlation-id 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 77
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 30
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-06