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.
You can install the package via composer:
composer require keepsuit/laravel-opentelemetryYou can publish the config file with:
php artisan vendor:publish --provider="Keepsuit\LaravelOpenTelemetry\LaravelOpenTelemetryServiceProvider" --tag="opentelemetry-config"This is the contents of the published config file:
…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:
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,
];
});
}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 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 tracingexcluded_methods: list of HTTP methods to exclude from tracingallowed_headers: list of headers to include in the tracesensitive_headers: list of headers with sensitive data to hide in the traceMetrics:
http.server.request.duration (histogram, seconds) - Request processing timeYou can disable this instrumentation by setting OTEL_INSTRUMENTATION_HTTP_SERVER to false or removing HttpServerInstrumentation::class from the config.
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.
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:
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 durationYou can disable this instrumentation by setting OTEL_INSTRUMENTATION_HTTP_CLIENT to false or removing HttpClientInstrumentation::class from the config.
Database queries are automatically traced. A span is created for each query executed.
Metrics:
db.client.operation.duration (histogram, seconds) - Duration of database client operationsYou can disable this instrumentation by setting OTEL_INSTRUMENTATION_QUERY to false or removing QueryInstrumentation::class from the config.
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 commands are automatically traced. A span is created for each command executed.
Metrics:
db.client.operation.duration (histogram, seconds) - Duration of Redis client operationsYou can disable this instrumentation by setting OTEL_INSTRUMENTATION_REDIS to false or removing RedisInstrumentation::class from the config.
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 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 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 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 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:
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:
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,
],
],
// ...
],
// ...
];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.
This package provides tracing capabilities and utilities that integrate with the instrumentations described above.
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:
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;
Tracer::newSpan('my custom trace')->measure(function () {
// do something
});Alternatively you can manage the span manually:
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:
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:
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 headersSampling 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 makes decisions at the beginning of a trace, based on the trace ID and parent context. This is fast and works well for:
Head sampling is configured in the traces.sampler section of the config file.
Tail sampling makes decisions after a trace has completed, allowing you to keep only "interesting" traces while discarding the rest. For example, you can:
[!NOTE] Tail sampling implemented at the application-level should only be used fo
No open issues yet, or sync has not completed.