Laravel instrumentation
Instrument a Laravel application with OpenTelemetry and send traces, logs, and metrics to Maple.
This guide instruments a Laravel application with the keepsuit/laravel-opentelemetry package. The package hooks OpenTelemetry into Laravel’s HTTP kernel, database, queue, cache and logging, and sends traces, logs and metrics to Maple. For Symfony or plain PHP, see PHP instrumentation.
To have a coding agent do this setup, use the maple-onboard skill. To check an existing setup, use maple-audit.
Prerequisites
- PHP 8.2+ and Laravel 11.31 or later (the versions the current package release supports)
- Composer
- An ingest key from Settings → Ingestion in Maple. Use the private key (
maple_sk_…) for server applications.
Install
composer require keepsuit/laravel-opentelemetry
Publish the config file so you can turn individual instrumentations on and off later:
php artisan vendor:publish \
--provider="Keepsuit\LaravelOpenTelemetry\LaravelOpenTelemetryServiceProvider" \
--tag="opentelemetry-config"
The package pulls in the OpenTelemetry PHP SDK and OTLP exporter, and registers its middleware and instrumentation through a service provider.
Configure
The package reads the standard OpenTelemetry environment variables and exports traces, metrics and logs over OTLP by default. Set the variables to Maple’s ingest endpoint and your ingest key:
# .env
OTEL_SERVICE_NAME=my-laravel-app
OTEL_TRACES_EXPORTER=otlp
OTEL_METRICS_EXPORTER=otlp
OTEL_LOGS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.maple.dev
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer%20YOUR_INGEST_KEY"
OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production,vcs.repository.url.full=https://github.com/acme/my-laravel-app"
For an EU organization, use https://ingest.eu.maple.dev. The endpoint is the base URL; the exporters append /v1/traces, /v1/metrics and /v1/logs. With OTEL_EXPORTER_OTLP_ENDPOINT unset, the published config falls back to http://localhost:4318, which is Maple Local on the same machine.
The package applies OTEL_EXPORTER_OTLP_HEADERS to every signal. If you run an older release that ignores it, set OTEL_, OTEL_ and OTEL_ to the same value.
An ingest key can only write telemetry to your organization. It cannot read data or call the Maple API. Committing it, as the fallback for traces_headers, metrics_headers and logs_headers in the published config/opentelemetry.php (with Maple’s URL as the endpoint fallback), means a deploy that is missing an environment variable cannot silently turn telemetry off. That is fine for private code. In a public repository, keep the key in .env or your secret store.
http/protobuf or http/json
Maple accepts both encodings. The difference is on the PHP side:
http/protobufneeds a protobuf implementation. The pure-PHPgoogle/protobuflibrary works but is slow. For production, install the protobuf C extension (pecl install protobuf, thenextension=protobuf.so).http/jsonneeds no extension. If protobuf export fails in your environment, for example in a minimal Laravel Sail container, setOTEL_.EXPORTER_ OTLP_ PROTOCOL=http/ json
Auto-instrumentation
Once installed, the package creates telemetry for:
- HTTP requests: a server span per incoming request, and the
http.server.request.durationmetric - HTTP client: a client span for each request made with the
Httpfacade, with the trace context propagated to the service you call, and thehttp.client.request.durationmetric - Database: a span per Eloquent or query builder statement, and the
db.client.operation.durationmetric - Queue jobs: producer and consumer spans, with context carried across the queue
- Redis: commands
- Cache: hits and misses, recorded as span events
- Views and Livewire components: a span per render
- Console commands: a span per run, for the commands you list in the
ConsoleInstrumentationconfig - Events: recorded as span events, with configurable exclusions
Each instrumentation can be turned off with its OTEL_INSTRUMENTATION_* variable (for example OTEL_) or in the published config/opentelemetry.php.
Custom spans
Use the Tracer facade. measure() starts the span, makes it the active span while the callback runs, and ends it:
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;
Tracer::newSpan('process-order')
->setAttributes([
'order.id' => $orderId,
'payment.method' => 'card',
])
->measure(fn () => $this->chargePayment($orderId));
To record an exception or set the status yourself, start and activate the span by hand. The span has the OpenTelemetry PHP API (setAttribute, recordException, setStatus):
use Keepsuit\LaravelOpenTelemetry\Facades\Tracer;
use OpenTelemetry\API\Trace\StatusCode;
$span = Tracer::newSpan('process-order')->start();
$scope = $span->activate();
try {
return $this->chargePayment($orderId);
} catch (\Throwable $e) {
$span->recordException($e);
$span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
throw $e;
} finally {
$scope->detach();
$span->end();
}
Service map edges come from instrumented client spans that propagate traceparent to an instrumented callee, not from attributes such as peer.service. See Service map.
The facade also has Tracer::traceId(), Tracer::activeSpan() and Tracer::propagationHeaders() for correlating logs and propagating context by hand.
For custom metrics, use the Meter facade:
use Keepsuit\LaravelOpenTelemetry\Facades\Meter;
Meter::counter('orders.processed', 'orders', 'Orders processed')->add(1);
Attributes Maple uses
Most attributes are optional. These unlock specific features.
Commits and GitHub
Set vcs.ref.head.revision (the full 40-character commit SHA) and vcs.repository.url.full on the resource. vcs.ref.head.revision drives deploy markers and the Recent deploys panel on each service page. With the GitHub integration, the two attributes also drive commit hover cards on traces. Read the SHA from your CI or host at build time, such as GITHUB_SHA or VERCEL_GIT_COMMIT_SHA, not from git at runtime:
export OTEL_RESOURCE_ATTRIBUTES="vcs.repository.url.full=https://github.com/acme/api,vcs.ref.head.revision=$GITHUB_SHA"
Databases
The package records a span for every Eloquent and query builder statement, with the standard db.* attributes. db.system.name and db.namespace draw the database node on the service map, and db.query.text groups statements into query shapes. Keep OTEL_INSTRUMENTATION_QUERY on. See Database queries for the full list.
Log correlation
The package adds a log channel named otlp that sends log records to Maple with the active trace ID attached. Route logs to it with LOG_CHANNEL=otlp, or add it to a stack so logs also keep going to your files:
// config/logging.php
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'otlp'],
],
],
Logs then line up with the trace that produced them in Maple.
Local mode and Docker (Laravel Sail)
To send to Maple Local running on your host, the exporter inside the Sail container must reach back to the host. Maple Local binds 127.0.0.1 by default, which a container cannot reach, so start it on all interfaces:
maple start --host 0.0.0.0
A non-loopback bind exposes ingest, the UI and queries to your network without authentication, so do this only on a trusted network. See the CLI reference.
Then point the exporter at host.docker.internal and the OTLP/HTTP port 4318:
# .env (Sail container sending to Maple Local on the host)
OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/json
- Maple Local needs no
Authorizationheader, so drop the headers variable. - On Linux hosts where
host.docker.internaldoes not resolve, addextra_to the service inhosts: ["host. docker. internal:host- gateway"] docker-compose.yml.
Sampling
The package keeps every trace by default. It configures the sampler through its own variables, not the standard OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG. To keep a share of new traces with a parent-based ratio sampler:
# .env
OTEL_TRACES_SAMPLER_TYPE=traceidratio
OTEL_TRACES_SAMPLER_PARENT=true
OTEL_TRACES_SAMPLER_TRACEIDRATIO_RATIO=0.1
OTEL_ (the default) wraps the ratio in a parent-based sampler, so a request that arrives with a traceparent header follows the caller’s decision and a trace is kept or dropped as a whole across services. The same settings live under traces.sampler in config/opentelemetry.php. Sampling changes how Maple counts requests, so read Sampling and throughput before you lower the ratio.
Shutdown and flush
Telemetry is exported in batches. Under PHP-FPM or php artisan serve, the package registers the SDK with auto-shutdown, so each request’s spans, logs and metrics are flushed when PHP finishes the request. You do not need to call anything.
Octane, Horizon, queue workers and Reverb are long-lived processes. The package detects them and flushes every 60 seconds and when the process stops. To change that:
# .env
OTEL_WORKER_MODE_FLUSH_INTERVAL=10
# or flush after every request or job:
OTEL_WORKER_MODE_FLUSH_AFTER_EACH_ITERATION=true
Stop workers with a signal they handle (SIGTERM, or php artisan queue:restart and php artisan octane:stop), so the last batch goes out. A worker killed with SIGKILL loses whatever it had not flushed.
Verify
- Start your application and send it a few requests, or dispatch a queued job.
- In Maple, open Explore → Traces. If nothing appears after a minute, see Troubleshooting.
- Each request should show up as one trace with a single root server span, named after the method and route (for example
GET /orders), and child spans for the queries and jobs it triggered. - If you routed logs to the
otlpchannel, open Explore → Logs and check that log lines link to their traces.
Your service also appears on the Services page once its first spans arrive.
Troubleshooting
401responses. The key is wrong, was copied from the other region, or the header is malformed.OTEL_EXPORTER_OTLP_HEADERStakesAuthorization=Bearer%20YOUR_. See Ingest API status codes.INGEST_ KEY - Protocol. Maple accepts OTLP over HTTP as protobuf or JSON. If exports fail with protobuf errors, switch to
http/json, or install the protobuf extension. - Network. From inside the container or server, run
curl -i https://ingest.maple.dev/. Any HTTP status code means the host can reach Maple. A timeout or DNS error means a firewall or proxy is blocking outbound HTTPS.v1/ traces -X POST - Nothing exported. Run
php artisan config:clearafter changing.env; a cached config keeps the old values. Check thatOTEL_SDK_DISABLEDis not set totrue.