Download the PHP package keepsuit/laravel-opentelemetry without Composer
On this page you can find all versions of the php package keepsuit/laravel-opentelemetry. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download keepsuit/laravel-opentelemetry
More information about keepsuit/laravel-opentelemetry
Files in keepsuit/laravel-opentelemetry
Package laravel-opentelemetry
Short Description OpenTelemetry integration for laravel
License MIT
Homepage https://github.com/keepsuit/laravel-opentelemetry
Informations about the package laravel-opentelemetry
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:
You can publish the config file with:
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:
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 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 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.
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:
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:
By class name:
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:
Alternatively you can manage the span manually:
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:
Other utility methods are available on the Tracer facade:
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 for single-service scenarios. For multi-service tail sampling, use the OpenTelemetry Collector instead because it has visibility into the complete trace across all services.
When tail sampling is enabled, it waits for the trace to complete (or a timeout defined by the decision_wait config) before making a sampling decision based on the entire trace.
It evaluates the trace against a set of rules in the order they appear in the configuration, and the first rule that returns Keep or Drop determines the outcome.
If none of the rules make a decision, the configured head sampler is used. (We suggest using the traceidratio sampler as fallback).
By default, two tail sampling rules are included:
- Errors Rule: keeps traces with any span that has an error status
- Slow Trace Rule: keeps traces that exceed a duration threshold (default 2000ms)
Tail sampling can be configured with these environment variables (or editing the config file directly):
| Variable | Description | Default |
|---|---|---|
OTEL_TRACES_TAIL_SAMPLING_ENABLED |
Enable tail sampling | false |
OTEL_TRACES_TAIL_SAMPLING_DECISION_WAIT |
Maximum time to wait for trace completion before making a decision (in milliseconds) | 5000 |
OTEL_TRACES_TAIL_SAMPLING_RULE_KEEP_ERRORS |
Enable the built-in Errors Rule | true |
OTEL_TRACES_TAIL_SAMPLING_RULE_SLOW_TRACES |
Enable the built-in Slow Trace Rule | true |
OTEL_TRACES_TAIL_SAMPLING_SLOW_TRACES_THRESHOLD_MS |
Duration threshold for the Slow Trace Rule (in milliseconds) | 2000 |
Custom Rules
You can create custom tail sampling rules by implementing the TailSamplingRuleInterface:
Then register your custom rule in the configuration:
Logs Context
When starting a trace with provided instrumentation, the trace id is automatically injected in the log context. This allows to correlate logs with traces.
If you are starting the root trace manually,
you should call Tracer::updateLogContext() to inject the trace id in the log context.
[!NOTE] When using the OpenTelemetry logs driver (
otlp), the trace id is automatically injected in the log context without the need to callTracer::updateLogContext().
Metrics
The Meter facade provide methods to create metric instruments such as counters, gauges, and histograms.
The supported instruments are:
- Counter
- ObservableCounter
- UpDownCounter
- ObservableUpDownCounter
- Gauge
- ObservableGauge
- Histogram
There is also a batchObserve method to record multiple measurements at once.
[!NOTE] Instruments are cached by name to prevent duplicate instrument creation in the same Meter instance.
Example usage:
Metrics Temporality
The OTLP exporter supports setting a preferred temporality for exported metrics with the OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE env variable.
The supported values are Delta and Cumulative.
If not set, the exporter and SDK defaults apply.
Logs
This package provides a custom log channel that allows to process logs with OpenTelemetry instrumentation.
This package injects a log channel named otlp that can be used to send logs to OpenTelemetry using laravel default log system.
As an alternative, you can use the Logger facade to send logs directly to OpenTelemetry:
Worker Mode
When Laravel is running in worker mode (e.g., Octane, Horizon, Queue workers), the application runs as a long-lived process that handles multiple requests or jobs in a single process lifecycle.
By default, exports are batched and flushed periodically or on process shutdown.
The worker_mode.flush_after_each_iteration config option allows to flush telemetry at the end of each iteration.
Worker mode is automatically detected using built-in detectors (for Laravel octane, horizon and queue workers), but you can also implement custom detectors for other runtimes.
Worker mode can be configured with these environment variables (or editing the config file directly):
| Variable | Description | Default |
|---|---|---|
OTEL_WORKER_MODE_FLUSH_AFTER_EACH_ITERATION |
Enable per-iteration flushing | false |
OTEL_WORKER_MODE_COLLECT_INTERVAL |
Metrics collection interval in seconds for worker mode | 60 |
If OTEL_WORKER_MODE_FLUSH_AFTER_EACH_ITERATION is true, the per-iteration flush behavior is used and the periodic collection interval is ignored.
Development Setup
To simplify development, a Makefile is provided. The project runs in a Docker container that mirrors your host user's UID and GID to avoid permission issues.
Available Makefile Commands
| Command | Description |
|---|---|
make build |
Builds the Docker image with your UID/GID for proper file permissions. |
make start |
Starts the containers in the background using Docker Compose. |
make stop |
Stops and removes the containers. |
make shell |
Starts the containers (if needed) and opens a Bash shell in the app one. |
make test |
Runs the test suite via Composer inside the app container. |
make lint |
Runs the linter via Composer inside the app container. |
📝 Before using
make shell, ensure the container is running (make startin another terminal).
Testing
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
- Fabio Capucci
- Aurimas Niekis
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-opentelemetry with dependencies
illuminate/contracts Version ^11.31 || ^12.0 || ^13.0
illuminate/support Version ^11.31 || ^12.0 || ^13.0
open-telemetry/api Version ^1.7
open-telemetry/context Version ^1.4
open-telemetry/exporter-otlp Version ^1.3
open-telemetry/sdk Version ^1.9
open-telemetry/sem-conv Version ^1.38
spatie/laravel-package-tools Version ^1.16
thecodingmachine/safe Version ^2.0 || ^3.0