Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Correlation Id Laravel Package

bilfeldt/laravel-correlation-id

Laravel middleware that ensures every request has a globally unique Correlation-ID (and echoes any client Request-ID), adds them to the request/response headers, and injects both into the global log context for easier tracing across services, APIs, and jobs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require bilfeldt/laravel-correlation-id
    
  2. Register middleware (choose one based on Laravel version):

    • Laravel 11: Add to bootstrap/app.php:
      ->withMiddleware(function (Middleware $middleware) {
          $middleware->prepend(\Bilfeldt\CorrelationId\Middleware\CorrelationIdMiddleware::class);
          $middleware->prepend(\Bilfeldt\CorrelationId\Middleware\ClientRequestIdMiddleware::class);
          $middleware->prepend(\Bilfeldt\CorrelationId\Middleware\LogContextMiddleware::class);
      })
      
    • Laravel 10/9: Add to app/Http/Kernel.php (order matters—place these first):
      protected $middleware = [
          \Bilfeldt\CorrelationId\Middleware\CorrelationIdMiddleware::class,
          \Bilfeldt\CorrelationId\Middleware\ClientRequestIdMiddleware::class,
          \Bilfeldt\CorrelationId\Middleware\LogContextMiddleware::class,
          // ... other middleware
      ];
      
  3. First use case: Access IDs in a controller or service:

    $correlationId = request()->getCorrelationId(); // e.g., "a1b2c3d4..."
    $clientRequestId = request()->getClientRequestId(); // e.g., "client-provided-id"
    

Implementation Patterns

Core Workflow

  1. Request Entry:

    • CorrelationIdMiddleware generates a UUID and attaches it to:
      • Request header: Correlation-ID
      • Response header: Correlation-ID
    • ClientRequestIdMiddleware echoes the client’s X-Request-ID header in the response.
  2. Context Propagation:

    • LogContextMiddleware injects IDs into Laravel’s global log context (via Log::sharedContext()).
    • Example log entry:
      {
        "level": "info",
        "message": "User logged in",
        "context": {
          "correlation_id": "a1b2c3d4...",
          "request_id": "client-provided-id"
        }
      }
      
  3. Job Queues:

    • IDs are automatically included in job payloads. Retrieve them in job handlers:
      $job->payload()['data']['correlation_id']; // Access via $job->payload()
      
    • Best practice: Use request()->getCorrelationId() in job dispatchers to ensure consistency:
      MyJob::dispatch()->onQueue('high')->withContext([
          'correlation_id' => request()->getCorrelationId(),
      ]);
      
  4. Error Handling:

    • Extend App\Exceptions\Handler to include IDs in error reports:
      protected function context(): array {
          return array_merge(parent::context(), [
              'correlation_id' => request()->getCorrelationId(),
              'request_id' => request()->getClientRequestId(),
          ]);
      }
      

Integration Tips

  • API Clients: Ensure downstream services expect Correlation-ID headers. Example (PHP cURL):
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Correlation-ID: ' . request()->getCorrelationId(),
    ]);
    
  • Testing: Mock the Request macros in tests:
    $request->shouldReceive('getCorrelationId')->andReturn('test-id-123');
    
  • Legacy Systems: Use getUniqueId() (alias for getCorrelationId()) for backward compatibility.

Gotchas and Tips

Pitfalls

  1. Middleware Order:

    • Critical: Place CorrelationIdMiddleware first in the stack. If another middleware modifies the request before this runs, the ID may be lost.
    • Order dependency: LogContextMiddleware must run after CorrelationIdMiddleware to capture IDs.
  2. Binary Responses:

    • The package avoids modifying binary responses (e.g., file downloads) to prevent corruption. Test edge cases like:
      return response()->file('path/to/file.pdf');
      
  3. Queue Workers:

    • If jobs are processed by separate workers (e.g., Laravel Horizon), ensure the worker’s Request instance is initialized with the ID. Use the JobContextMiddleware (if available in future versions) or manually inject IDs:
      $job->handle(request()->create('/dummy', 'GET', [], [], [], ['correlation_id' => request()->getCorrelationId()]));
      
  4. Log Context Leakage:

    • Avoid logging sensitive data in the shared context. Use Log::withContext() sparingly:
      Log::withContext(['correlation_id' => $id])->info('Safe log message');
      

Debugging Tips

  • Missing IDs?:

    • Verify middleware is registered globally (not route-specific).
    • Check for typos in class names (e.g., CorrelationIdMiddleware vs. CorrelationId).
    • Use dd(request()->headers->all()) to inspect headers during development.
  • Log Context Not Appearing:

    • Ensure LogContextMiddleware is enabled and runs after ID generation.
    • Check your logging driver (e.g., Monolog) supports shared contexts.
  • Job IDs Not Propagating:

    • Confirm the job’s payload() includes the data key. If not, manually attach IDs:
      MyJob::dispatch()->withContext(['correlation_id' => request()->getCorrelationId()]);
      

Extension Points

  1. Custom ID Generation:

    • Override the default UUID generator by binding a custom CorrelationIdGenerator:
      $this->app->bind(\Bilfeldt\CorrelationId\Contracts\CorrelationIdGenerator::class, function () {
          return new CustomGenerator();
      });
      
  2. Header Names:

    • Change header names via config (if added in future versions) or override middleware:
      $middleware->setHeaderName('X-Custom-ID');
      
  3. Additional Context:

    • Extend LogContextMiddleware to include extra data (e.g., user agent):
      Log::sharedContext()->set('user_agent', request()->userAgent());
      
  4. Testing Utilities:

    • Create a test helper to simulate correlation IDs:
      function setTestCorrelationId(string $id) {
          app()->make(\Illuminate\Http\Request::class)->setCorrelationId($id);
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky