PHPackages                             overtrue/laravel-open-telemetry - 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. overtrue/laravel-open-telemetry

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

overtrue/laravel-open-telemetry
===============================

This package provides a simple way to add OpenTelemetry to your Laravel application.

0.0.32(6mo ago)166.8k—0%1MITPHPPHP &gt;=8.4

Since Apr 24Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/overtrue/laravel-open-telemetry)[ Packagist](https://packagist.org/packages/overtrue/laravel-open-telemetry)[ GitHub Sponsors](https://github.com/overtrue)[ RSS](/packages/overtrue-laravel-open-telemetry/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (36)Used By (0)

Laravel OpenTelemetry
=====================

[](#laravel-opentelemetry)

> **⚠️ Deprecated**: This package is no longer maintained. Please consider using [keepsuit/laravel-opentelemetry](https://github.com/keepsuit/laravel-opentelemetry) instead.

[![Latest Version on Packagist](https://camo.githubusercontent.com/57d4cfa3d963c9178d9239bee24fe65c45859b25edbc8d60bdad671e0d542b1c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f766572747275652f6c61726176656c2d6f70656e2d74656c656d657472792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/overtrue/laravel-open-telemetry)[![Total Downloads](https://camo.githubusercontent.com/35c5393329af3d542fbcbfcd56abd581c394c4cfe7c5872997398c7a5695c19e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f766572747275652f6c61726176656c2d6f70656e2d74656c656d657472792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/overtrue/laravel-open-telemetry)

This package provides a simple way to add OpenTelemetry to your Laravel application.

Features
--------

[](#features)

- ✅ **Zero Configuration**: Works out of the box with sensible defaults.
- ✅ **Laravel Native**: Deep integration with Laravel's lifecycle and events.
- ✅ **Octane &amp; FPM Support**: Full compatibility with Laravel Octane and traditional FPM setups.
- ✅ **Powerful `Measure` Facade**: Provides an elegant API for manual, semantic tracing.
- ✅ **Automatic Tracing**: Built-in watchers for cache, database, HTTP clients, queues, and more.
- ✅ **Flexible Configuration**: Control traced paths, headers, and watchers to fit your needs.
- ✅ **Standards Compliant**: Adheres to OpenTelemetry Semantic Conventions.

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

[](#installation)

You can install the package via composer:

```
composer require overtrue/laravel-open-telemetry
```

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

[](#configuration)

> **Important Note for Octane Users**
>
> When using Laravel Octane, it is **highly recommended** to set `OTEL_*` environment variables at the machine or process level (e.g., in your Dockerfile, `docker-compose.yml`, or Supervisor configuration) rather than relying solely on the `.env` file.
>
> This is because some OpenTelemetry components, especially those enabled by `OTEL_PHP_AUTOLOAD_ENABLED`, are initialized before the Laravel application fully boots and reads the `.env` file. Setting them as system-level environment variables ensures they are available to the PHP process from the very beginning.

This package uses the standard OpenTelemetry environment variables for configuration. Add these to your `.env` file for basic setup:

### Basic Configuration

[](#basic-configuration)

```
# Enable OpenTelemetry PHP SDK auto-loading
OTEL_PHP_AUTOLOAD_ENABLED=true

# Service identification
OTEL_SERVICE_NAME=my-laravel-app
OTEL_SERVICE_VERSION=1.0.0

# Exporter configuration (console for dev, otlp for prod)
OTEL_TRACES_EXPORTER=console
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf

# Context propagation
OTEL_PROPAGATORS=tracecontext,baggage
```

### Package Configuration

[](#package-configuration)

For package-specific settings, publish the configuration file:

```
php artisan vendor:publish --provider="Overtrue\LaravelOpenTelemetry\OpenTelemetryServiceProvider" --tag=config
```

This will create a `config/otel.php` file. Here are the key options:

#### Enabling/Disabling Tracing

[](#enablingdisabling-tracing)

You can completely enable or disable tracing for the entire application. This is useful for performance tuning or disabling tracing in certain environments.

```
// config/otel.php
'enabled' => env('OTEL_ENABLED', true),
```

Set `OTEL_ENABLED=false` in your `.env` file to disable all tracing.

**Log Format**: All OpenTelemetry logs are prefixed with `[laravel-open-telemetry]` for easy identification and filtering.

#### Filtering Requests and Headers

[](#filtering-requests-and-headers)

You can control which requests are traced and which headers are recorded to enhance performance and protect sensitive data. All patterns support wildcards (`*`) and are case-insensitive.

- **`ignore_paths`**: A list of request paths to exclude from tracing. Useful for health checks, metrics endpoints, etc. ```
    'ignore_paths' => ['health*', 'telescope*', 'horizon*'],
    ```
- **`allowed_headers`**: A list of HTTP header patterns to include in spans. If empty, no headers are recorded. ```
    'allowed_headers' => ['x-request-id', 'user-agent', 'authorization'],
    ```
- **`sensitive_headers`**: A list of header patterns whose values will be masked (replaced with `***`). ```
    'sensitive_headers' => ['authorization', 'cookie', 'x-api-key', '*-token'],
    ```

#### Watchers

[](#watchers)

You can enable or disable specific watchers to trace different parts of your application.

```
// config/otel.php
'watchers' => [
    \Overtrue\LaravelOpenTelemetry\Watchers\CacheWatcher::class => env('OTEL_CACHE_WATCHER_ENABLED', true),
    \Overtrue\LaravelOpenTelemetry\Watchers\QueryWatcher::class => env('OTEL_QUERY_WATCHER_ENABLED', true),
    // ...
],
```

Usage
-----

[](#usage)

The package is designed to work with minimal manual intervention, but it also provides a powerful `Measure` facade for creating custom spans.

### Automatic Tracing

[](#automatic-tracing)

With the default configuration, the package automatically traces:

- Incoming HTTP requests.
- Database queries (`QueryWatcher`).
- Cache operations (`CacheWatcher`).
- Outgoing HTTP client requests (`HttpClientWatcher`).
- Thrown exceptions (`ExceptionWatcher`).
- Queue jobs (`QueueWatcher`).
- ...and more, depending on the enabled [watchers](#watchers).

### Creating Custom Spans with `Measure::trace()`

[](#creating-custom-spans-with-measuretrace)

For tracing specific blocks of code, the `Measure::trace()` method is the recommended approach. It automatically handles span creation, activation, exception recording, and completion.

```
use Overtrue\LaravelOpenTelemetry\Facades\Measure;

Measure::trace('process-user-data', function ($span) use ($user) {
    // Add attributes to the span
    $span->setAttribute('user.id', $user->id);

    // Your business logic here
    $this->process($user);

    // Add an event to mark a point in time within the span
    $span->addEvent('User processing finished');
});
```

The `trace` method will:

- Start a new span.
- Execute the callback.
- Automatically record and re-throw any exceptions that occur within the callback.
- End the span when the callback completes.

### Advanced Span Creation with SpanBuilder

[](#advanced-span-creation-with-spanbuilder)

For more control over span lifecycle, you can use the `SpanBuilder` directly through `Measure::span()`. The SpanBuilder provides several methods for different use cases:

#### Basic Span Creation (Recommended for most cases)

[](#basic-span-creation-recommended-for-most-cases)

```
// Create a span without activating its scope (safer for async operations)
$span = Measure::span('my-operation')
    ->setAttribute('operation.type', 'data-processing')
    ->setSpanKind(SpanKind::KIND_INTERNAL)
    ->start(); // Returns SpanInterface

// Your business logic here
$result = $this->processData();

// Remember to end the span manually
$span->end();
```

#### Span with Activated Scope

[](#span-with-activated-scope)

```
// Create a span and activate its scope (for nested operations)
$startedSpan = Measure::span('parent-operation')
    ->setAttribute('operation.type', 'user-workflow')
    ->setSpanKind(SpanKind::KIND_INTERNAL)
    ->startAndActivate(); // Returns StartedSpan

// Any spans created within this block will be children of this span
$childSpan = Measure::span('child-operation')->start();
$childSpan->end();

// The StartedSpan automatically manages scope cleanup
$startedSpan->end(); // Ends span and detaches scope
```

#### Span with Context (For Manual Propagation)

[](#span-with-context-for-manual-propagation)

```
// Create a span and get both span and context for manual management
[$span, $context] = Measure::span('async-operation')
    ->setAttribute('operation.async', true)
    ->startWithContext(); // Returns [SpanInterface, ContextInterface]

// Use context for propagation (e.g., in HTTP headers)
$headers = Measure::propagationHeaders($context);

// Your async operation here
$span->end();
```

### Using Semantic Spans

[](#using-semantic-spans)

To promote standardization, the package provides semantic helper methods that create spans with attributes conforming to OpenTelemetry's [Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/).

#### Database Spans

[](#database-spans)

```
// Manually trace a block of database operations
$user = Measure::database('SELECT', 'users'); // Quick shortcut for database operations
// Or use the general trace method for more complex operations
$user = Measure::trace('repository:find-user', function ($span) use ($userId) {
    $span->setAttribute('db.statement', "SELECT * FROM users WHERE id = ?");
    $span->setAttribute('db.table', 'users');
    return User::find($userId);
});
```

*Note: If `QueryWatcher` is enabled, individual queries are already traced. This is useful for tracing a larger transaction or a specific business operation involving multiple queries.*

#### HTTP Client Spans

[](#http-client-spans)

```
// Quick shortcut for HTTP client requests
$response = Measure::httpClient('POST', 'https://api.example.com/users');
// Or use the general trace method for more control
$response = Measure::trace('api-call', function ($span) {
    $span->setAttribute('http.method', 'POST');
    $span->setAttribute('http.url', 'https://api.example.com/users');
    return Http::post('https://api.example.com/users', $data);
});
```

#### Custom Spans

[](#custom-spans)

```
// For any custom operation, use the general trace method
$result = Measure::trace('process-payment', function ($span) use ($payment) {
    $span->setAttribute('payment.amount', $payment->amount);
    $span->setAttribute('payment.currency', $payment->currency);

    // Your business logic here
    return $this->processPayment($payment);
});
```

### Retrieving the Current Span

[](#retrieving-the-current-span)

You can access the currently active span anywhere in your code.

```
use Overtrue\LaravelOpenTelemetry\Facades\Measure;

$currentSpan = Measure::activeSpan();
$currentSpan->setAttribute('custom.attribute', 'some_value');
```

### Watchers

[](#watchers-1)

The package includes several watchers that automatically create spans for common Laravel operations. You can enable or disable them in `config/otel.php`.

- **`CacheWatcher`**: Traces cache hits, misses, writes, and forgets.
- **`QueryWatcher`**: Traces the execution of every database query.
- **`HttpClientWatcher`**: Traces all outgoing HTTP requests made with Laravel's `Http` facade.
- **`ExceptionWatcher`**: Traces all exceptions thrown in your application.
- **`QueueWatcher`**: Traces jobs being dispatched, processed, and failing.
- **`RedisWatcher`**: Traces Redis commands.
- **`AuthenticateWatcher`**: Traces authentication events like login, logout, and failed attempts.

### Trace ID Injection Middleware

[](#trace-id-injection-middleware)

The package includes middleware to add a `X-Trace-Id` header to your HTTP responses, which is useful for debugging.

You can apply it to specific routes:

```
// In your routes/web.php or routes/api.php
Route::middleware('otel.traceid')->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
});
```

Or apply it globally in `app/Http/Kernel.php`:

```
// app/Http/Kernel.php

// In the $middlewareGroups property for 'web' or 'api'
protected $middlewareGroups = [
    'web' => [
        // ...
        \Overtrue\LaravelOpenTelemetry\Http\Middleware\AddTraceId::class,
    ],
    // ...
];
```

Environment Variables Reference
-------------------------------

[](#environment-variables-reference)

### Core OpenTelemetry Variables

[](#core-opentelemetry-variables)

VariableDescriptionDefaultExample`OTEL_PHP_AUTOLOAD_ENABLED`Enable PHP SDK auto-loading`false``true``OTEL_SERVICE_NAME`Service name`unknown_service``my-laravel-app``OTEL_SERVICE_VERSION`Service version`null``1.0.0``OTEL_TRACES_EXPORTER`Trace exporter type`otlp``console`, `otlp``OTEL_EXPORTER_OTLP_ENDPOINT`OTLP endpoint URL`http://localhost:4318``https://api.honeycomb.io``OTEL_EXPORTER_OTLP_PROTOCOL`OTLP protocol`http/protobuf``http/protobuf`, `grpc``OTEL_PROPAGATORS`Context propagators`tracecontext,baggage``tracecontext,baggage,b3``OTEL_TRACES_SAMPLER`Sampling strategy`parentbased_always_on``always_on`, `traceidratio``OTEL_TRACES_SAMPLER_ARG`Sampler argument`null``0.1``OTEL_RESOURCE_ATTRIBUTES`Resource attributes`null``key1=value1,key2=value2`Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [overtrue](https://github.com/overtrue)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance70

Regular maintenance activity

Popularity31

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 95.6% 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 ~18 days

Recently: every ~10 days

Total

32

Last Release

189d ago

PHP version history (2 changes)0.0.1PHP &gt;=8.2

0.0.10PHP &gt;=8.4

### Community

Maintainers

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

---

Top Contributors

[![overtrue](https://avatars.githubusercontent.com/u/1472352?v=4)](https://github.com/overtrue "overtrue (86 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (4 commits)")

---

Tags

laravel-packageopentelemetryopentelemetry-laravelopentelemetry-phpopentracingtracing-library

###  Code Quality

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/overtrue-laravel-open-telemetry/health.svg)

```
[![Health](https://phpackages.com/badges/overtrue-laravel-open-telemetry/health.svg)](https://phpackages.com/packages/overtrue-laravel-open-telemetry)
```

###  Alternatives

[keepsuit/laravel-opentelemetry

OpenTelemetry integration for laravel

142347.8k](/packages/keepsuit-laravel-opentelemetry)[open-telemetry/sdk

SDK for OpenTelemetry PHP.

2222.9M248](/packages/open-telemetry-sdk)[open-telemetry/symfony-sdk-bundle

OpenTelemetry Symfony integration

1182.6k4](/packages/open-telemetry-symfony-sdk-bundle)[open-telemetry/opentelemetry-auto-pdo

OpenTelemetry auto-instrumentation for PDO

111.2M1](/packages/open-telemetry-opentelemetry-auto-pdo)[open-telemetry/opentelemetry-auto-wordpress

OpenTelemetry auto-instrumentation for Wordpress

17166.0k](/packages/open-telemetry-opentelemetry-auto-wordpress)

PHPackages © 2026

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