Tracing
- Introduction
- Exporting traces
- What's traced
- Your own spans
- Traces across services
- Exporting another way
Introduction
When a page or API endpoint is slow, a trace shows you exactly where the time went. Each request produces a timeline made up of timed spans for every database query, cache lookup, and outgoing HTTP request, making it easy to spot bottlenecks. Laravel exports traces using OpenTelemetry to any tool that accepts OTLP, such as Sentry or Grafana.
You don't need to instrument your application manually to get started. Requests, console commands, queued jobs, database queries, and everything else listed in What's traced already emit spans, so once you enable the exporter, traces begin flowing immediately.
Exporting traces
To export traces, add Laravel's opentelemetry feature to laravel-rust in your Cargo.toml:
1[dependencies]2laravel-rust = { version = "0.1", features = ["database-postgres", "opentelemetry"] }1[dependencies]2laravel-rust = { version = "0.1", features = ["database-postgres", "opentelemetry"] }
Then configure OpenTelemetry's standard environment variables in your .env file. Laravel starts exporting traces as soon as an endpoint is configured:
1OTEL_SERVICE_NAME=storefront2OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:43181OTEL_SERVICE_NAME=storefront2OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
To try tracing locally, you may run Jaeger in Docker. It accepts traces at the endpoint above and serves its UI at http://localhost:16686:
1docker run --rm -p 4318:4318 -p 16686:16686 jaegertracing/jaeger1docker run --rm -p 4318:4318 -p 16686:16686 jaegertracing/jaeger
These are the environment variables most applications configure:
| Variable | What it does |
|---|---|
OTEL_EXPORTER_OTLP_ENDPOINT |
The base URL to send traces to. Laravel appends /v1/traces. |
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT |
The full URL to send traces to, instead of appending /v1/traces to the base URL. |
OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_TRACES_HEADERS |
Request headers to include, such as an API key: x-api-key=secret. |
OTEL_SERVICE_NAME |
The service name your tracing tool groups traces under. Defaults to APP_NAME. |
OTEL_RESOURCE_ATTRIBUTES |
Additional service attributes, such as deployment.environment.name=production. |
OTEL_SDK_DISABLED |
Set to true to disable exporting without removing your endpoint configuration. |
Laravel batches and exports spans in the background so incoming requests never wait on your tracing tool. If the collector is unreachable, your application keeps running and logs the error. Before a console command exits or the server shuts down, Laravel flushes any buffered spans.
Sentry
Sentry accepts traces over OTLP. Find your project's OTLP traces endpoint and public key under Client Keys (DSN) in your project settings, then add them to .env:
1OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://o123456.ingest.us.sentry.io/api/7891011/integration/otlp/v1/traces2OTEL_EXPORTER_OTLP_TRACES_HEADERS="x-sentry-auth=sentry sentry_key=your-public-key"1OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://o123456.ingest.us.sentry.io/api/7891011/integration/otlp/v1/traces2OTEL_EXPORTER_OTLP_TRACES_HEADERS="x-sentry-auth=sentry sentry_key=your-public-key"
To forward errors to Sentry as well, check out the logging guide's section on Sentry.
Sampling
By default, Laravel exports every trace. On a busy production application, exporting 100% of traces can get expensive, so you may configure a sampler to keep a percentage of them:
1OTEL_TRACES_SAMPLER=parentbased_traceidratio2OTEL_TRACES_SAMPLER_ARG=0.11OTEL_TRACES_SAMPLER=parentbased_traceidratio2OTEL_TRACES_SAMPLER_ARG=0.1
With these settings, Laravel keeps 10% of traces that originate in your service. When a request continues an existing trace from another service, Laravel follows that upstream sampling decision instead so traces are never split in half.
OTEL_TRACES_SAMPLER accepts always_on, always_off, traceidratio, parentbased_always_on (the default), parentbased_always_off, and parentbased_traceidratio.
What's traced
Laravel names each span and attaches attributes following OpenTelemetry's semantic conventions:
| Span | Name |
|---|---|
| Each HTTP request, except the health route | The method and route, such as GET /users/{user}, with HTTP in place of a non-standard method such as PURGE |
| Each console command, except long-running commands | The command's name, such as reports:generate |
| Each attempt of a queued job | The job's name |
| Each scheduled task | The task's description |
| Each tick | The tick's name |
Each background task started with task::background |
background |
| Each advance of a workflow run | workflow and the workflow's name, such as workflow users.onboard |
| Each attempt of a workflow step | step and the step's name, such as step charge card |
| Each attempt of an outgoing HTTP request | The HTTP method, such as GET, or HTTP for a non-standard method |
| Each database query | The SQL operation and table, such as SELECT orders, or the operation alone when no table applies |
| Each database transaction begun, committed, or rolled back | BEGIN, COMMIT, or ROLLBACK, and SAVEPOINT or RELEASE for a nested transaction |
| Each cache operation | The operation name, such as cache.get |
| Each Redis command or pipeline | The command name, such as GET, or PIPELINE |
| Each email rendered and sent | mail.render or mail.send |
| Each SMS sent | sms.send |
Laravel marks a span as failed when a request returns a 5xx status, a command exits with an error, a job attempt, scheduled task, tick, background task, workflow run, or workflow step fails, or a database query, cache operation, Redis command, outgoing request, mail send, or SMS send fails.
When your own code fails a span, such as a handler returning laravel::Error::msg("the payment gateway timed out"), the span shows your error's message, so your tracing tool tells you why it failed. When the error came from Laravel, the span shows a short summary instead, because the error's message can quote your users' data. For example, a PostgreSQL error that quotes the value it couldn't cast shows database error 22P02, a rejected outgoing request shows HTTP 404 without the response body, and a Resend rejection shows Resend rejected the email with HTTP 422 without Resend's message, and a value Laravel couldn't decode or encode as JSON shows JSON error without quoting the value. The summary wins even when your code adds context to Laravel's error. Every failed span also records error.type, such as 22P02, 404, or timeout, so you can group failures in your tracing tool. Your logs and error reports still receive the full error.
Spans never include bound query parameters, Redis command arguments, phone numbers, or email addresses, subjects, and bodies. Laravel replaces every literal in a query's SQL with ?, so where email = '[email protected]' is exported as where email = ?. An outgoing request's URL keeps its query string's parameter names but replaces their values with REDACTED.
When the HTTP client retries a request, each attempt is a span of its own, and each retry records http.request.resend_count. A request that gets a 503 and then succeeds shows as one failed span followed by one successful span.
Laravel exports a request's path, such as /reset-password/8f2c..., and each cache key as written, and it exports the messages you log inside a span as they are. Don't put secrets in paths, cache keys, or your own log messages.
When OpenTelemetry tracing is enabled, JSON log lines also include the active span's trace_id and span_id so log tools can link directly to the trace.
Your own spans
Laravel's built-in spans show you which query was slow, but not which part of your own code triggered it. To see your own functions in a trace, wrap them in custom spans using the tracing crate, which your application already depends on. Your span becomes a child of the active request or command span, and any queries or outgoing requests inside it become children of your span.
The #[tracing::instrument] attribute wraps an entire function in a span named after it. For example, this function finds a user's most popular posts for a weekly digest email:
1use laravel::prelude::*;23use crate::models::{Post, User};45#[tracing::instrument(skip_all, fields(user.id = user.id))]6pub async fn popular_posts(user: &User) -> laravel::Result<Vec<Post>> {7 let posts = Post::query()8 .filter(Post::user_id.eq(user.id) & Post::votes.gt(100))9 .order_by(Post::votes.desc())10 .limit(5)11 .get()12 .await?;1314 Ok(posts)15}1use laravel::prelude::*;23use crate::models::{Post, User};45#[tracing::instrument(skip_all, fields(user.id = user.id))]6pub async fn popular_posts(user: &User) -> laravel::Result<Vec<Post>> {7 let posts = Post::query()8 .filter(Post::user_id.eq(user.id) & Post::votes.gt(100))9 .order_by(Post::votes.desc())10 .limit(5)11 .get()12 .await?;1314 Ok(posts)15}
By default, #[tracing::instrument] records every function argument as a span attribute. Passing skip_all keeps sensitive fields like the user's email address out of your traces, while fields(user.id = user.id) records only the user's ID.
To wrap a single future in a span instead of an entire function, import tracing::Instrument and call .instrument(...):
1use tracing::Instrument;23let posts = load_posts(&user)4 .instrument(tracing::info_span!("popular_posts", user.id = user.id))5 .await?;1use tracing::Instrument;23let posts = load_posts(&user)4 .instrument(tracing::info_span!("popular_posts", user.id = user.id))5 .await?;
Laravel exports spans at the debug level and above, so trace_span! stays out of exported traces. Any messages you log inside a span at or above your configured log level are attached to that span as events. Laravel's own log lines are attached with only their IDs, counts, durations, and names, and a line about an error shows the error's summary, as a failed span does. The log mailer's and SMS sender's previews of a message stay in your local log, and so do lines that other libraries log, such as SQLx's statement lines, which quote your SQL with its values.
A background task spawned with task::spawn inherits the active span automatically. A task spawned with tokio::spawn does not, so its queries appear in separate traces.
Traces across services
When one service calls another, Laravel propagates traces automatically using W3C Trace Context headers. An incoming request carrying a traceparent header continues that upstream trace, and every outgoing HTTP request sends a traceparent header so downstream services can join your trace.
A queued job also continues the trace of the request or command that dispatched it, even when a worker on another server processes the job. Likewise, when the scheduler runs a scheduled console command, Laravel links the command's span beneath the scheduled task so the entire schedule:run appears in a single trace. Because Laravel passes the trace context through the TRACEPARENT and TRACESTATE environment variables, external programs run via exec or shell that read those variables join the same trace automatically.
Exporting another way
The OTEL_* environment variables configure an OTLP-over-HTTP exporter. If you need a different exporter, such as one from a vendor crate or a stdout exporter for local debugging, build your own OpenTelemetry tracer provider. First, add the OpenTelemetry crates to Cargo.toml using the same version Laravel uses so your provider's type matches what tracer_provider expects:
1opentelemetry_sdk = "0.33"2opentelemetry-stdout = "0.33"1opentelemetry_sdk = "0.33"2opentelemetry-stdout = "0.33"
Then register the provider with tracer_provider inside with_logging in src/app.rs. For example, this provider prints each span to your terminal while you inspect span attributes locally:
1use laravel::prelude::*;2use opentelemetry_sdk::trace::SdkTracerProvider;34Application::configure()5 .with_logging(|logging, _| {6 let provider = SdkTracerProvider::builder()7 .with_batch_exporter(opentelemetry_stdout::SpanExporter::default())8 .build();910 logging.tracer_provider(provider);11 })1use laravel::prelude::*;2use opentelemetry_sdk::trace::SdkTracerProvider;34Application::configure()5 .with_logging(|logging, _| {6 let provider = SdkTracerProvider::builder()7 .with_batch_exporter(opentelemetry_stdout::SpanExporter::default())8 .build();910 logging.tracer_provider(provider);11 })
When a custom provider is registered, Laravel uses it instead of the OTEL_* exporter and shuts it down cleanly when your application exits. Because Laravel installs the provider before the Tokio runtime starts, exporters that require an active Tokio runtime during initialization (such as OTLP over gRPC) will panic.