PHPackages                             jftecnologia/laravel-tracing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. jftecnologia/laravel-tracing

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

jftecnologia/laravel-tracing
============================

Distributed tracing for Laravel — propagates correlation IDs and request IDs across HTTP requests, queued jobs, and outgoing HTTP client calls.

v1.0.3(1mo ago)0662↓50%11MITPHPPHP ^8.4CI passing

Since Feb 12Pushed 1mo agoCompare

[ Source](https://github.com/jftecnologia/laravel-tracing)[ Packagist](https://packagist.org/packages/jftecnologia/laravel-tracing)[ Docs](https://github.com/jftecnologia/laravel-tracing)[ RSS](/packages/jftecnologia-laravel-tracing/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (18)Versions (7)Used By (1)

Laravel Tracing
===============

[](#laravel-tracing)

[![Latest Version on Packagist](https://camo.githubusercontent.com/cfd2695186e974cf30868cd6753b969d2c99de6e4cf2c42213e030dc0cee1ceb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a667465636e6f6c6f6769612f6c61726176656c2d74726163696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jftecnologia/laravel-tracing)[![GitHub Tests Action Status](https://camo.githubusercontent.com/d84712b7ffa1e948d6611e0d52b0dde234c13b8f0fed94b3949e1001ef3e4efe/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a667465636e6f6c6f6769612f6c61726176656c2d74726163696e672f74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/jftecnologia/laravel-tracing/actions?query=workflow%3Atests+branch%3Amaster)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/86942c8495cdb39a7a2a29536e4e961d48bc6debdcaf4df3f7d9a90325a909bc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a667465636e6f6c6f6769612f6c61726176656c2d74726163696e672f6669782d7068702d636f64652d7374796c652e796d6c3f6272616e63683d6d6173746572266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/jftecnologia/laravel-tracing/actions?query=workflow%3A%22fix-php-code-style-issues%22+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/eceec2614f9109e84bed813339cba09d3cf62697b0899552780136195e3c1c4f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a667465636e6f6c6f6769612f6c61726176656c2d74726163696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jftecnologia/laravel-tracing)

**Lightweight, plug-and-play request tracing for Laravel applications.**

Laravel Tracing automatically tracks requests across your application using correlation IDs and request IDs. It seamlessly propagates tracing context through queued jobs, HTTP requests, and external API calls — making it easy to correlate logs, debug distributed systems, and trace user sessions end-to-end.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Overview](#overview)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Usage Examples](#usage-examples)
- [Custom Tracing Sources](#custom-tracing-sources)
- [Troubleshooting](#troubleshooting)
- [Testing](#testing)
- [Credits](#credits)
- [License](#license)

---

Overview
--------

[](#overview)

In distributed and monolithic Laravel applications, tracking the origin and flow of requests is essential for debugging, monitoring, and log correlation. Without standardized tracing identifiers, it's difficult to:

- Correlate log entries across services
- Debug issues spanning multiple requests or jobs
- Track a user session end-to-end
- Trace requests through queues and external HTTP calls

**Laravel Tracing solves this** by automatically attaching tracing headers (correlation ID, request ID) to every request, propagating them through queued jobs, and forwarding them to external services.

### Why Use Laravel Tracing?

[](#why-use-laravel-tracing)

- ✅ **Simple Setup**: One-time middleware registration in `bootstrap/app.php`
- ✅ **Session Persistence**: Correlation IDs survive across multiple requests from the same user
- ✅ **Job Propagation**: Tracing context automatically flows into queued jobs
- ✅ **HTTP Client Integration**: Forward tracing headers to external APIs with `Http::withTracing()`
- ✅ **Fully Extensible**: Add custom tracing sources (user ID, tenant ID, app version) without modifying package code
- ✅ **Environment-Aware**: Toggle features via config file and environment variables
- ✅ **Lightweight**: No external dependencies beyond Laravel core

---

Features
--------

[](#features)

- **Built-In Tracing**:

    - **Correlation ID** (`X-Correlation-Id`): Tracks user sessions across multiple requests
    - **Request ID** (`X-Request-Id`): Uniquely identifies each HTTP request
- **Session Persistence**: Correlation IDs persist across requests from the same user session (via Laravel session/cookies)
- **Job Propagation**: Tracing values are automatically serialized with job payloads and restored during execution
- **HTTP Client Integration**: Opt-in support for forwarding tracing headers to external services via `Http::withTracing()`
- **Custom Tracing Sources**: Easily add custom tracings (user ID, tenant ID, app version) via config or runtime registration
- **Global Accessor**: Access all tracing values from anywhere in your application via the `LaravelTracing` facade
- **Configurable**: Control header names, enable/disable tracings, and customize behavior via config file and environment variables
- **Fully Tested**: Comprehensive test suite using PestPHP

---

Requirements
------------

[](#requirements)

- **PHP**: 8.4 or higher
- **Laravel**: 12 or higher

---

Installation
------------

[](#installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require jftecnologia/laravel-tracing
```

### Step 2: Register Middleware

[](#step-2-register-middleware)

**Important**: Laravel 12 does not support automatic middleware registration via package discovery. You must manually register the tracing middleware in your `bootstrap/app.php` file:

```
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use JuniorFontenele\LaravelTracing\Middleware\IncomingTracingMiddleware;
use JuniorFontenele\LaravelTracing\Middleware\OutgoingTracingMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Register tracing middleware to web group (for session-based correlation ID persistence)
        $middleware->appendToGroup('web', IncomingTracingMiddleware::class);
        $middleware->appendToGroup('web', OutgoingTracingMiddleware::class);

        // Optional: Register to api group if you want tracing on API routes
        // Note: API routes won't have session persistence, so correlation ID will be generated per request
        $middleware->appendToGroup('api', IncomingTracingMiddleware::class);
        $middleware->appendToGroup('api', OutgoingTracingMiddleware::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
```

**Important Notes**:

- The middleware must be registered to the `web` middleware group (or after Laravel's `StartSession` middleware) to ensure session persistence for correlation IDs
- If registered globally or before `StartSession`, correlation IDs will not persist across requests
- Unlike Laravel 11 and earlier versions, Laravel 12 does not support automatic middleware registration through package discovery

### Alternative: Route-Specific Registration

[](#alternative-route-specific-registration)

If you prefer to apply tracing only to specific routes:

```
// In routes/web.php
Route::middleware([
    IncomingTracingMiddleware::class,
    OutgoingTracingMiddleware::class,
])->group(function () {
    Route::get('/traced', function () {
        return response()->json(['status' => 'traced']);
    });
});
```

### Step 3: Publish Configuration (Optional)

[](#step-3-publish-configuration-optional)

To customize tracing behavior (header names, enable/disable features, add custom tracings), publish the configuration file:

```
php artisan vendor:publish --tag=laravel-tracing-config
```

This creates `config/laravel-tracing.php` where you can customize all package settings.

### Verification

[](#verification)

Make a request to your application and check the response headers:

```
curl -I http://localhost:8000
```

You should see:

```
X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000
X-Request-Id: 123e4567-e89b-12d3-a456-426614174000

```

---

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

Access tracing values from anywhere in your application:

```
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;

// Get correlation ID
$correlationId = LaravelTracing::correlationId();

// Get request ID
$requestId = LaravelTracing::requestId();

// Get all tracing values
$allTracings = LaravelTracing::all();
// Returns: ['correlation_id' => '...', 'request_id' => '...']
```

### Use in Log Context

[](#use-in-log-context)

```
use Illuminate\Support\Facades\Log;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;

Log::info('User action performed', LaravelTracing::all());
```

**Log output:**

```
{
  "message": "User action performed",
  "correlation_id": "550e8400-e29b-41d4-a716-446655440000",
  "request_id": "123e4567-e89b-12d3-a456-426614174000"
}
```

### Tracing in Queued Jobs

[](#tracing-in-queued-jobs)

Tracing values are automatically propagated to queued jobs:

```
// Dispatch a job from a controller
dispatch(new ProcessOrder($orderId));
```

```
// Inside the job handler
class ProcessOrder implements ShouldQueue
{
    public function handle(): void
    {
        // Access original correlation ID from the dispatching request
        $correlationId = LaravelTracing::correlationId();

        Log::info('Processing order', [
            'correlation_id' => $correlationId, // Same as dispatching request
            'request_id' => LaravelTracing::requestId(), // Preserved from dispatch
        ]);
    }
}
```

### Forward Tracing to External APIs

[](#forward-tracing-to-external-apis)

```
use Illuminate\Support\Facades\Http;

// Attach all tracing headers to outgoing HTTP request
$response = Http::withTracing()
    ->get('https://api.example.com/data');
```

**The external service receives:**

```
X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000
X-Request-Id: 123e4567-e89b-12d3-a456-426614174000

```

---

Configuration
-------------

[](#configuration)

### Configuration File Structure

[](#configuration-file-structure)

After publishing the config (`php artisan vendor:publish --tag=laravel-tracing-config`), you'll have access to `config/laravel-tracing.php`:

```
return [
    // Global enable/disable toggle
    'enabled' => env('LARAVEL_TRACING_ENABLED', true),

    // Accept tracing headers from external requests
    'accept_external_headers' => env('LARAVEL_TRACING_ACCEPT_EXTERNAL_HEADERS', false),

    // Define tracing sources
    'tracings' => [
        'correlation_id' => [
            'enabled' => true,
            'header' => env('LARAVEL_TRACING_CORRELATION_ID_HEADER', 'X-Correlation-Id'),
            'source' => 'JuniorFontenele\LaravelTracing\Tracings\Sources\CorrelationIdSource',
        ],
        'request_id' => [
            'enabled' => true,
            'header' => env('LARAVEL_TRACING_REQUEST_ID_HEADER', 'X-Request-Id'),
            'source' => 'JuniorFontenele\LaravelTracing\Tracings\Sources\RequestIdSource',
        ],
    ],

    // HTTP client integration
    'http_client' => [
        'enabled' => env('LARAVEL_TRACING_HTTP_CLIENT_ENABLED', false),
    ],
];
```

### Configuration Options

[](#configuration-options)

#### Global Settings

[](#global-settings)

KeyTypeDefaultDescription`enabled`bool`true`Master switch for the entire package. When `false`, all tracing operations are skipped (zero overhead).`accept_external_headers`bool`false`When `true`, tracing values are read from incoming request headers (forwarded by upstream services). When `false`, values are always generated fresh.**Environment Variables:**

- `LARAVEL_TRACING_ENABLED` - Enable/disable package globally
- `LARAVEL_TRACING_ACCEPT_EXTERNAL_HEADERS` - Accept external headers

#### Per-Tracing Settings

[](#per-tracing-settings)

Each entry in the `tracings` array supports:

KeyTypeRequiredDescription`enabled`boolYesWhether this tracing source is active`header`stringYesHTTP header name for reading/writing this value`source`stringYesFully-qualified class name of the `TracingSource` implementation**Built-In Tracings:**

- **`correlation_id`**: Session-level identifier (persists across multiple requests from the same user)

    - Default header: `X-Correlation-Id`
    - Environment variable: `LARAVEL_TRACING_CORRELATION_ID_HEADER`
- **`request_id`**: Request-level identifier (unique per HTTP request)

    - Default header: `X-Request-Id`
    - Environment variable: `LARAVEL_TRACING_REQUEST_ID_HEADER`

#### HTTP Client Settings

[](#http-client-settings)

KeyTypeDefaultDescription`http_client.enabled`bool`false`When `true`, `Http::withTracing()` is available globally. When `false`, it's opt-in per request.**Environment Variable:**

- `LARAVEL_TRACING_HTTP_CLIENT_ENABLED`

### Configuration Examples

[](#configuration-examples)

#### Disable Tracing in Local Environment

[](#disable-tracing-in-local-environment)

```
# .env.local
LARAVEL_TRACING_ENABLED=false
```

#### Customize Header Names

[](#customize-header-names)

```
# .env
LARAVEL_TRACING_CORRELATION_ID_HEADER=X-Trace-Id
LARAVEL_TRACING_REQUEST_ID_HEADER=X-Span-Id
```

#### Disable External Header Acceptance (Security)

[](#disable-external-header-acceptance-security)

If your application is publicly exposed and you don't want to accept correlation IDs from untrusted sources:

```
# .env.production
LARAVEL_TRACING_ACCEPT_EXTERNAL_HEADERS=false
```

> **Security Note**: When `accept_external_headers` is `true`, the package will use correlation/request IDs sent by clients. Only enable this if you trust your upstream services (API gateways, load balancers, internal services).

#### Enable HTTP Client Tracing Globally

[](#enable-http-client-tracing-globally)

```
# .env
LARAVEL_TRACING_HTTP_CLIENT_ENABLED=true
```

When enabled, all HTTP requests automatically include tracing headers without calling `withTracing()`:

```
// Tracing headers automatically attached
Http::get('https://api.example.com/data');
```

---

Usage Examples
--------------

[](#usage-examples)

### Example 1: Accessing Tracing Values in Controllers

[](#example-1-accessing-tracing-values-in-controllers)

```
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;

class OrderController extends Controller
{
    public function store(Request $request)
    {
        // Get all tracing values
        $tracings = LaravelTracing::all();

        // Get specific values
        $correlationId = LaravelTracing::correlationId();
        $requestId = LaravelTracing::requestId();

        // Use in business logic
        $order = Order::create([
            'user_id' => $request->user()->id,
            'correlation_id' => $correlationId, // Store in database for audit
        ]);

        return response()->json(['order_id' => $order->id]);
    }
}
```

### Example 2: Using Tracings in Log Context

[](#example-2-using-tracings-in-log-context)

```
use Illuminate\Support\Facades\Log;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;

// In any part of your application
Log::info('Processing payment', array_merge(
    ['amount' => 99.99, 'currency' => 'USD'],
    LaravelTracing::all() // Add all tracing values to log context
));
```

**Log output:**

```
{
  "message": "Processing payment",
  "amount": 99.99,
  "currency": "USD",
  "correlation_id": "550e8400-e29b-41d4-a716-446655440000",
  "request_id": "123e4567-e89b-12d3-a456-426614174000",
  "timestamp": "2026-02-11T10:30:00Z"
}
```

### Example 3: Session Persistence (Same Correlation ID Across Requests)

[](#example-3-session-persistence-same-correlation-id-across-requests)

**Request 1:**

```
curl -I http://localhost:8000/api/cart/add
```

**Response:**

```
X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000
X-Request-Id: 123e4567-e89b-12d3-a456-426614174000
Set-Cookie: laravel_session=...

```

**Request 2 (same session):**

```
curl -I http://localhost:8000/api/cart/checkout \
  -H "Cookie: laravel_session=..."
```

**Response:**

```
X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000  ← Same correlation ID!
X-Request-Id: 789e0123-e45b-67c8-d901-234567890abc      ← New request ID

```

The correlation ID persists across requests from the same session, enabling you to trace all actions from a single user.

### Example 4: Tracing in Queued Jobs

[](#example-4-tracing-in-queued-jobs)

```
// Dispatch job from controller
class OrderController extends Controller
{
    public function store(Request $request)
    {
        $order = Order::create($request->all());

        // Correlation ID and request ID are automatically serialized with the job
        ProcessOrder::dispatch($order);

        return response()->json(['order_id' => $order->id]);
    }
}
```

```
// Job handler
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use JuniorFontenele\LaravelTracing\Facades\LaravelTracing;

class ProcessOrder implements ShouldQueue
{
    use Queueable;

    public function __construct(public Order $order) {}

    public function handle(): void
    {
        // Tracing values from the original request are restored
        Log::info('Job processing order', [
            'order_id' => $this->order->id,
            'correlation_id' => LaravelTracing::correlationId(), // Same as dispatch request
            'request_id' => LaravelTracing::requestId(),         // Preserved from dispatch
        ]);

        // Process order...
    }
}
```

**Result**: All logs from the job execution include the same correlation ID as the dispatching request, making it easy to trace the entire flow.

### Example 5: Multiple Jobs Share Correlation ID

[](#example-5-multiple-jobs-share-correlation-id)

```
// Dispatch multiple jobs from the same request
public function bulkProcess(Request $request)
{
    foreach ($request->orders as $order) {
        ProcessOrder::dispatch($order);
        SendInvoice::dispatch($order);
        UpdateInventory::dispatch($order);
    }

    return response()->json(['status' => 'queued']);
}
```

**All dispatched jobs** (`ProcessOrder`, `SendInvoice`, `UpdateInventory`) will share the same correlation ID, allowing you to filter logs by correlation ID to see all related job executions.

### Example 6: Forwarding Tracings to External APIs

[](#example-6-forwarding-tracings-to-external-apis)

```
use Illuminate\Support\Facades\Http;

// Call external service with tracing headers
public function fetchUserData(int $userId)
{
    $response = Http::withTracing()
        ->get("https://api.example.com/users/{$userId}");

    return $response->json();
}
```

**HTTP request sent to external service:**

```
GET /users/42 HTTP/1.1
Host: api.example.com
X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000
X-Request-Id: 123e4567-e89b-12d3-a456-426614174000

```

The external service can now log requests with the same correlation ID, enabling distributed tracing across services.

---

Custom Tracing Sources
----------------------

[](#custom-tracing-sources)

Laravel Tracing is fully extensible. You can add custom tracing sources to track additional context like:

- User ID
- Tenant ID (for multi-tenant applications)
- Application version
- Custom business identifiers

### Quick Example: Add User ID Tracing

[](#quick-example-add-user-id-tracing)

#### Step 1: Create Custom Source Class

[](#step-1-create-custom-source-class)

```
// app/Tracings/UserIdSource.php
