PHPackages                             xman12/laravel-zipkin-tracer - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. xman12/laravel-zipkin-tracer

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

xman12/laravel-zipkin-tracer
============================

The tracing for Zipkin for your application based on Laravel

1.0.1(10mo ago)04Apache-2.0PHP

Since Apr 7Pushed 10mo ago1 watchersCompare

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

READMEChangelogDependencies (1)Versions (4)Used By (0)

Laravel Zipkin Tracer
=====================

[](#laravel-zipkin-tracer)

[![PHP Version](https://camo.githubusercontent.com/c5e8da782b1a0673c08b4f474108036d2cc973470eed2d5d89d48e8c8475eee6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322d626c75652e737667)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/3413b01aac22dae409978d6232e25fbf749bacd26b92908c407fb16ea97d70d7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25334525334431302e302d7265642e737667)](https://laravel.com)[![License](https://camo.githubusercontent.com/48c3918479c6ea40d65216332adbf6c7a89400e32b69faf50a750b905d214b76/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d417061636865253230322e302d677265656e2e737667)](LICENSE)

A specialized Laravel module that provides automatic tracing for HTTP requests, SQL queries, and custom spans with seamless Zipkin integration.

🎯 Overview
----------

[](#-overview)

In modern microservice application development, it's crucial to have the ability to track request execution across various services. Distributed tracing allows developers to understand how requests flow through the system, identify bottlenecks, and diagnose performance issues.

**Laravel Zipkin Tracer** is a specialized module for Laravel that provides automatic tracing of HTTP requests, SQL queries, and allows creation of custom spans for integration with Zipkin — a popular distributed tracing system.

✨ Features
----------

[](#-features)

### 🔄 Automatic Tracing

[](#-automatic-tracing)

- **HTTP Requests**: Method, URL, status code, request/response size, execution time, exceptions
- **SQL Queries**: Query text, execution time, file and line location, transactions (begin, commit, rollback)
- **HTTP Client Requests**: Outgoing HTTP requests via Laravel HTTP Client, headers, status codes, connection errors

### 🛠️ Custom Spans

[](#️-custom-spans)

- Create custom spans for business logic tracking
- Support for nested spans (parent-child relationships)
- Flexible tagging system
- Exception handling and error tracking

### ⚡ Performance Optimized

[](#-performance-optimized)

- Asynchronous data sending
- Minimal overhead
- Efficient file system storage
- Non-blocking operations

🏗️ Architecture
---------------

[](#️-architecture)

### System Architecture

[](#system-architecture)

[![system_architecture.png](system_architecture.png)](system_architecture.png)

### Storage Architecture

[](#storage-architecture)

[![storage_architecture.png](storage_architecture.png)](storage_architecture.png)

### Data Collection Flow

[](#data-collection-flow)

[![data_collect.png](data_collect.png)](data_collect.png)

📦 Installation
--------------

[](#-installation)

### Requirements

[](#requirements)

- PHP ^8.2
- Laravel ^10
- openzipkin/zipkin ^3.2

### Install via Composer

[](#install-via-composer)

```
composer require xman12/laravel-zipkin-tracer
```

### Setup Provider

[](#setup-provider)

Add the provider to `app/bootstrap/providers.php`:

```
return [
    App\Providers\AppServiceProvider::class,
    ZipkinTracerProvider::class,
];
```

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --tag=zipkin-tracer
```

⚙️ Configuration
----------------

[](#️-configuration)

### Environment Variables

[](#environment-variables)

Add these variables to your `.env` file:

```
ZIPKIN_TRACER_ENABLE=true
ZIPKIN_TRACER_STORAGE_PATH=/path/to/storage/zipkin_tracer
ZIPKIN_TRACER_SERVICE_NAME=my-service
ZIPKIN_TRACER_ENDPOINT=http://127.0.0.1:9411/api/v2/spans
```

### Configuration Options

[](#configuration-options)

VariableDescriptionDefault`ZIPKIN_TRACER_ENABLE`Enable/disable tracing`false``ZIPKIN_TRACER_STORAGE_PATH`Local storage path for JSON files`storage_path('zipkin_tracer')``ZIPKIN_TRACER_SERVICE_NAME`Service name in Zipkin`Zipkin-service``ZIPKIN_TRACER_ENDPOINT`Zipkin server endpoint`http://127.0.0.1:9411/api/v2/spans`### Setup Cron Job

[](#setup-cron-job)

Add this to your crontab for data synchronization:

```
# Sync data to Zipkin every minute
* * * * * php artisan zipkin-tracer:sync_data
```

🚀 Usage
-------

[](#-usage)

### Automatic Tracing

[](#automatic-tracing)

Once configured, the module automatically traces:

- **HTTP Requests**: All incoming HTTP requests
- **SQL Queries**: All database queries and transactions
- **HTTP Client**: All outgoing HTTP requests via Laravel HTTP Client

### Custom Spans

[](#custom-spans)

Create custom spans for business logic tracking:

```
/** @var CustomSpanService $customSpanService */
$customSpanService = app(CustomSpanService::class);

// Simple span
$span = $customSpanService->createSpan('user-registration', function () {
    // Business logic for user registration
    $user = User::create([
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]);

    return [
        'user_id' => $user->id,
        'registration_method' => 'email'
    ];
});

$customSpanService->addSpan($span);
```

### Nested Spans

[](#nested-spans)

Create parent-child span relationships:

```
// Child spans
$validationSpan = $customSpanService->createSpan('validate-user-data', function () {
    // Data validation logic
    return ['validation_passed' => true];
});

$emailSpan = $customSpanService->createSpan('send-welcome-email', function () {
    // Send welcome email
    return ['email_sent' => true];
});

// Parent span with children
$mainSpan = $customSpanService->createSpan('user-registration-process', function () {
    // Main logic
    return ['process_completed' => true];
}, [$validationSpan, $emailSpan]);

$customSpanService->addSpan($mainSpan);
```

📝 Examples
----------

[](#-examples)

### Example 1: API Endpoint Tracing

[](#example-1-api-endpoint-tracing)

```
// UserController.php
class UserController extends Controller
{
    public function show($id)
    {
        /** @var CustomSpanService $customSpanService */
        $customSpanService = app(CustomSpanService::class);

        $span = $customSpanService->createSpan('get-user-profile', function () use ($id) {
            $user = User::with(['profile', 'posts'])->findOrFail($id);

            return [
                'user_id' => $user->id,
                'profile_complete' => $user->profile ? true : false,
                'posts_count' => $user->posts->count()
            ];
        });

        $customSpanService->addSpan($span);

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

### Example 2: External API Tracing

[](#example-2-external-api-tracing)

```
// ExternalApiService.php
class ExternalApiService
{
    public function fetchUserData($userId)
    {
        /** @var CustomSpanService $customSpanService */
        $customSpanService = app(CustomSpanService::class);

        $span = $customSpanService->createSpan('external-api-call', function () use ($userId) {
            // Laravel HTTP Client is automatically traced
            $response = Http::get("https://api.external.com/users/{$userId}");

            return [
                'external_user_id' => $userId,
                'response_status' => $response->status(),
                'response_size' => strlen($response->body())
            ];
        });

        $customSpanService->addSpan($span);

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

### Example 3: Complex Business Logic Tracing

[](#example-3-complex-business-logic-tracing)

```
// OrderService.php
class OrderService
{
    public function processOrder($orderData)
    {
        /** @var CustomSpanService $customSpanService */
        $customSpanService = app(CustomSpanService::class);

        // Order validation
        $validationSpan = $customSpanService->createSpan('validate-order', function () use ($orderData) {
            $validator = Validator::make($orderData, [
                'items' => 'required|array',
                'customer_id' => 'required|exists:customers,id'
            ]);

            if ($validator->fails()) {
                throw new ValidationException($validator);
            }

            return ['validation_passed' => true];
        });

        // Inventory check
        $inventorySpan = $customSpanService->createSpan('check-inventory', function () use ($orderData) {
            foreach ($orderData['items'] as $item) {
                $product = Product::find($item['product_id']);
                if ($product->stock < $item['quantity']) {
                    throw new InsufficientStockException();
                }
            }

            return ['inventory_available' => true];
        });

        // Order creation
        $orderSpan = $customSpanService->createSpan('create-order', function () use ($orderData) {
            DB::transaction(function () use ($orderData) {
                $order = Order::create([
                    'customer_id' => $orderData['customer_id'],
                    'total_amount' => $this->calculateTotal($orderData['items'])
                ]);

                foreach ($orderData['items'] as $item) {
                    $order->items()->create($item);
                }
            });

            return ['order_created' => true];
        });

        // Main span
        $mainSpan = $customSpanService->createSpan('process-order-complete', function () {
            return ['order_processed' => true];
        }, [$validationSpan, $inventorySpan, $orderSpan]);

        $customSpanService->addSpan($mainSpan);
    }
}
```

🔄 Data Flow
-----------

[](#-data-flow)

### Data Structure

[](#data-structure)

Data is stored in JSON files with the following structure:

```
{
  "queries": [
    {
      "query": "SELECT * FROM users WHERE id = ?",
      "duration": 0.001234,
      "start_time": 1640995200.123,
      "execute_file": "/app/Http/Controllers/UserController.php",
      "execute_file_line": 45
    }
  ],
  "http_data": {
    "method": "GET",
    "url": "/api/users/1",
    "status_code": 200,
    "request_size": 1024,
    "response_size": 2048,
    "time": 0.045,
    "request_id": "req_123456"
  },
  "http_client_data": [
    {
      "method": "POST",
      "url": "https://api.external.com/data",
      "headers": {"Authorization": "Bearer token"},
      "duration_time": 0.123,
      "status_code": 201
    }
  ],
  "custom_spans": [
    {
      "name": "user-registration",
      "duration_time": 0.234,
      "tags": {"user_id": 123, "method": "email"}
    }
  ]
}
```

### When to Use Laravel Zipkin Tracer

[](#when-to-use-laravel-zipkin-tracer)

✅ **Recommended when:**

- You have a Laravel application
- Need simple and fast tracing setup
- Using Zipkin as tracing system
- Require minimal configuration

❌ **Not recommended when:**

- Need support for multiple tracing systems
- Require full OpenTelemetry compatibility
- Need advanced metrics capabilities
- Planning migration to other monitoring systems

📊 Monitoring &amp; Debugging
----------------------------

[](#-monitoring--debugging)

### Viewing Data in Zipkin

[](#viewing-data-in-zipkin)

After setting up synchronization, data will be available in the Zipkin web interface:

1. Open Zipkin UI (usually )
2. Select your service from the dropdown
3. Set the time range
4. View traces and spans

### Performance Analysis

[](#performance-analysis)

In Zipkin you can see:

- **Execution time** of each span
- **Dependencies** between services
- **Performance bottlenecks**
- **Errors** and exceptions
- **SQL queries** with execution time

### Common Debugging Scenarios

[](#common-debugging-scenarios)

1. **Slow Requests**: Analyze SQL query execution times
2. **External API Errors**: Review HTTP client requests
3. **Business Logic Issues**: Analyze custom spans
4. **Performance Issues**: Identify bottlenecks in request chains

📄 License
---------

[](#-license)

This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.

🙏 Acknowledgments
-----------------

[](#-acknowledgments)

- [Zipkin](https://zipkin.io/) - Distributed tracing system
- [Laravel](https://laravel.com/) - PHP web framework
- [OpenZipkin](https://github.com/openzipkin/zipkin-php) - PHP Zipkin library

📞 Support
---------

[](#-support)

- **Author**: Aleksandr Belyshev
- **Email**:
- **GitHub**:

---

**Laravel Zipkin Tracer** remains an excellent choice for quickly implementing tracing in Laravel applications with minimal effort and maximum efficiency.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance53

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~76 days

Total

2

Last Release

324d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d8967e637cf8597985252852f1cababe1cf71456d9a201335b734834f06d6ac1?d=identicon)[xman12](/maintainers/xman12)

---

Top Contributors

[![xman12](https://avatars.githubusercontent.com/u/3243905?v=4)](https://github.com/xman12 "xman12 (17 commits)")

---

Tags

zipkinlaravel-zipkin

### Embed Badge

![Health badge](/badges/xman12-laravel-zipkin-tracer/health.svg)

```
[![Health](https://phpackages.com/badges/xman12-laravel-zipkin-tracer/health.svg)](https://phpackages.com/packages/xman12-laravel-zipkin-tracer)
```

###  Alternatives

[openzipkin/zipkin

A Zipkin instrumentation for PHP

2774.3M36](/packages/openzipkin-zipkin)[bugsnag/bugsnag-psr-logger

Official Bugsnag PHP PSR Logger.

32132.5M2](/packages/bugsnag-bugsnag-psr-logger)[vinelab/tracing-laravel

Distributed tracing for Laravel made easy

80118.7k1](/packages/vinelab-tracing-laravel)[jcchavezs/zipkin-opentracing

A Zipkin bridge with OpenTracing

242.9M12](/packages/jcchavezs-zipkin-opentracing)[codemix/yii2-streamlog

A Yii 2 log target for streams in URL format

531.4M6](/packages/codemix-yii2-streamlog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
