Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-opentelemetry

> 后端框架
Open source

OpenTelemetry integration for laravel

173 stars0 likes1 views
WebsiteGitHub

About

OpenTelemetry integration for laravel

OpenTelemetry integration for laravel

OpenTelemetry is a collection of tools, APIs, and SDKs. Use it to instrument, generate, collect, and export telemetry data (metrics, logs, and traces) to help you analyze your software’s performance and behavior.

This package allows you to integrate OpenTelemetry in a Laravel application.

  • Installation
  • User Context
  • Instrumentations
    • Http Server Requests
    • Http Client
    • Database
    • Queue Jobs
    • Redis
    • Cache
    • Events
    • View
    • Livewire
    • Scout
    • Console Commands
  • Traces
    • Manual Traces
    • Trace Sampling
    • Logs Context
  • Metrics
    • Meter API
    • Metrics Temporality
  • Logs
  • Worker Mode
  • Development Setup
  • Testing
  • Changelog
  • Credits
  • License

Installation

You can install the package via composer:

bash
composer require keepsuit/laravel-opentelemetry

You can publish the config file with:

bash
php artisan vendor:publish --provider="Keepsuit\LaravelOpenTelemetry\LaravelOpenTelemetryServiceProvider" --tag="opentelemetry-config"

This is the contents of the published config file:

…

User Context

When user context is enabled (opentelemetry.user_context config option, enabled by default), the authenticated user id is automatically added as attribute user.id to all traces and logs. This allows to easily correlate traces and logs with the user that generated them.

You can customize the user context attributes by providing a custom resolver in you service provider:

php
use Keepsuit\LaravelOpenTelemetry\Facades\OpenTelemetry;
use Illuminate\Contracts\Auth\Authenticatable;

public function boot(): void
{
    OpenTelemetry::user(function (Authenticatable $user) {
        return [
            'user.id' => $user->getAuthIdentifier(),
            'user.email' => $user->email,
        ];
    });
}

Instrumentations

This package provides a set of instrumentations to automatically trace common operations in a Laravel application. Each instrumentation is configurable in config/opentelemetry.php and, when applicable, records default metrics described below.

Http Server Requests

Http server requests are automatically traced by injecting \Keepsuit\LaravelOpenTelemetry\Support\HttpServer\TraceRequestMiddleware::class to the global middlewares.

Configuration options:

  • excluded_paths: list of paths to exclude from tracing
  • excluded_methods: list of HTTP methods to exclude from tracing
  • allowed_headers: list of headers to include in the trace
  • sensitive_headers: list of headers with sensitive data to hide in the trace

Metrics:

  • http.server.request.duration (histogram, seconds) - Request processing time

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_HTTP_SERVER to false or removing HttpServerInstrumentation::class from the config.

Http Client

Http client requests are automatically traced by default, but you can set it to manual mode by setting manual to true in the config file.

When using manual mode, you need to call the withTrace method on the request builder to enable tracing for the request.

php
Http::withTrace()->get('https://example.com');

The low-cardinality url template cannot be automatically detected in http client requests like in server requests. By default, the span name will be only the HTTP method (e.g. GET) but you can manually resolve the url template from the request.

In your service provider:

php
use Keepsuit\LaravelOpenTelemetry\Instrumentation\HttpClientInstrumentation;
use Psr\Http\Message\RequestInterface;

public function boot(): void
{
    HttpClientInstrumentation::setRouteNameResolver(function (RequestInterface $request): ?string {
        return match (true) {
            str_starts_with($request->getUri()->getPath(), '/products/') => '/products/{id}',
            default => null,
        };
    });
}

Metrics:

  • http.client.request.duration (histogram, seconds) - Outgoing HTTP request duration

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_HTTP_CLIENT to false or removing HttpClientInstrumentation::class from the config.

Database

Database queries are automatically traced. A span is created for each query executed.

Metrics:

  • db.client.operation.duration (histogram, seconds) - Duration of database client operations

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_QUERY to false or removing QueryInstrumentation::class from the config.

Queue Jobs

Queue jobs are automatically traced. The instrumentation creates a parent span with kind PRODUCER when a job is dispatched and a child span with kind CONSUMER when the job is executed.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_QUEUE to false or removing QueueInstrumentation::class from the config.

Redis

Redis commands are automatically traced. A span is created for each command executed.

Metrics:

  • db.client.operation.duration (histogram, seconds) - Duration of Redis client operations

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_REDIS to false or removing RedisInstrumentation::class from the config.

Cache

Cache operations are recorded as events in the current active span.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_CACHE to false or removing CacheInstrumentation::class from the config.

Events

Events are recorded as events in the current active span. Some internal Laravel events are excluded by default and can be customized in the configuration.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_EVENT to false or removing EventInstrumentation::class from the config.

View

View rendering is automatically traced. A span is created for each rendered view.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_VIEW to false or removing ViewInstrumentation::class from the config.

Livewire

Livewire components rendering is automatically traced. A span is created for each rendered component.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_LIVEWIRE to false or removing LivewireInstrumentation::class from the config.

Console Commands

Console commands are not traced by default. You can trace console commands by adding them to the commands option of ConsoleInstrumentation.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_CONSOLE to false or removing ConsoleInstrumentation::class from the config.

You can add commands either by their signature or by their class name.

By signature:

php
use Keepsuit\LaravelOpenTelemetry\Instrumentation;

return [
    // ...
    
    /**
     * List of instrumentation used for application tracing
     */
    'instrumentation' => [
        // ...
        
        Instrumentation\ConsoleInstrumentation::class => [
            'enabled' => env('OTEL_INSTRUMENTATION_CONSOLE', true),
            'commands' => [
                'app:example-command',
             ],
        ],
        
        // ...
    ],
    
    // ...
];

By class name:

php
use Keepsuit\LaravelOpenTelemetry\Instrumentation;
use App\Console\Commands\ExampleCommand;

return [
    // ...
    
    /**
     * List of instrumentation used for application tracing
     */
    'instrumentation' => [
        // ...
        
        Instrumentation\ConsoleInstrumentation::class => [
            'enabled' => env('OTEL_INSTRUMENTATION_CONSOLE', true),
            'commands' => [
                ExampleCommand::class,
             ],
        ],
        
        // ...
    ],
    
    // ...
];

Scout

Tracing of laravel scout operations requires the opentelemetry php extension to be installed and enabled.

The instrumentation trace operations performed by laravel scout in a generic way without tracking engine-specific attributes.

You can disable this instrumentation by setting OTEL_INSTRUMENTATION_SCOUT to false or removing ScoutInstrumentation::class from the config.

Traces

This package provides tracing capabilities and utilities that integrate with the instrumentations described above.

Manual Traces

Spans can be manually created with the newSpan method on the Tracer facade. This method returns a SpanBuilder instance that can be used to customize and start the span.

The simplest way to create a custom trace is with measure method:

php
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;

Tracer::newSpan('my custom trace')->measure(function () {
    // do something
});

Alternatively you can manage the span manually:

php
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;

$span = Tracer::newSpan('my custom trace')->start();

// do something

$span->end();

With measure the span is automatically set to active (so it will be used as parent for new spans). With start you have to manually set the span as active:

php
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;

$span = Tracer::newSpan('my custom trace')->start();
$scope = $span->activate()

// do something

$scope->detach();
$span->end();

Other utility methods are available on the Tracer facade:

php
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;

Tracer::traceId(); // get the active trace id
Tracer::activeSpan(); // get the active span
Tracer::activeScope(); // get the active scope
Tracer::currentContext(); // get the current trace context (useful for advanced use cases)
Tracer::propagationHeaders(); // get the propagation headers required to propagate the trace to other services
Tracer::extractContextFromPropagationHeaders(array $headers); // extract the trace context from propagation headers

Trace Sampling

Sampling is the process of selecting which traces to collect and export. Since tracing every single request can be expensive at scale, sampling allows you to reduce costs while still maintaining visibility into your application's behavior.

This package supports two types of sampling that work together:

Aspect Head Sampling Tail Sampling
Decision time At span start At trace end
Criteria available Trace ID, parent context Full trace data, errors, duration
Use case Rate limiting, percentage sampling Error traces, slow traces, custom rules
Multi-service Works per-service Must use Collector

Head Sampling

Head sampling makes decisions at the beginning of a trace, based on the trace ID and parent context. This is fast and works well for:

  • Percentage-based sampling (e.g., keep 5% of traces)
  • Parent-based sampling (keep traces based on whether parent was sampled)
  • Rate limiting

Head sampling is configured in the traces.sampler section of the config file.

Tail Sampling

Tail sampling makes decisions after a trace has completed, allowing you to keep only "interesting" traces while discarding the rest. For example, you can:

  • Keep traces that contain errors
  • Keep traces that exceed a duration threshold
  • Define custom sampling rules based on span attributes
  • Fall back to ratio sampling for other traces

[!NOTE] Tail sampling implemented at the application-level should only be used fo

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPlaravelopentelemetrytracing

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架