Tracing
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 operation, and outgoing HTTP request, so you can see which step took the longest. Laravel exports traces using OpenTelemetry to any tool that accepts OTLP, such as Sentry or Grafana.
You don't need to instrument your application by hand to get started. Requests, console commands, queued jobs, database queries, and everything else listed in What's traced already record spans, so once you set an exporter's endpoint, your traces begin arriving in your tracing tool.
Exporting traces
To export traces, configure OpenTelemetry's standard environment variables in your .env file. Laravel starts exporting traces as soon as an endpoint is configured:
OTEL_SERVICE_NAME=storefront
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318To try tracing locally, you may run Jaeger in Docker. It accepts traces at the endpoint above and serves its UI at http://localhost:16686:
docker run --rm -p 4318:4318 -p 16686:16686 jaegertracing/jaegerThese 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 tool is unreachable, your application keeps running and logs a warning. Before a console command exits or the server shuts down, Laravel exports any spans that are still waiting. Until you configure an endpoint, Laravel doesn't record spans at all, so tracing costs your application nothing.
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 your .env file:
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://o123456.ingest.us.sentry.io/api/7891011/integration/otlp/v1/traces
OTEL_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 every trace can get expensive, so you may configure a sampler to keep a percentage of them:
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1With these settings, Laravel keeps 10% of the traces that originate in your service. When a request continues an existing trace from another service, Laravel follows that service's sampling decision instead, so traces are never split in half.
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}, or HTTP and the route for a method outside the standard ones |
| 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 name |
| Each tick | The tick's name |
Each background task started with r.Background or laravel.Background | background |
| Each advance of a workflow run | workflow and the workflow's name, such as workflow orders.checkout |
| Each try 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 |
| 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 |
| Each cache operation | The operation name, such as cache.get |
| Each Redis command, pipeline, or transaction | The command name, such as GET, or PIPELINE or MULTI |
| Each email rendered and sent | mail.render or mail.send |
| Each text message 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, a database query, cache operation, Redis command, email send, or SMS send fails, or an outgoing request gets a 4xx or 5xx response or no response at all. A cache read whose value doesn't decode as the type you asked for fails too.
When an outgoing request is retried, each attempt is a span of its own, and each one sends its own traceparent. For example, a request that gets a 503 and then a 200 on its retry shows as a failed GET span followed by a successful one, and the second records http.request.resend_count as 1.
What spans export
Traces often leave your infrastructure for a hosted tool, so Laravel keeps your users' data out of them. Spans never include bound query parameters, Redis command arguments, cached values, email addresses, subjects, and bodies, the phone numbers and text of SMS messages, or the bodies of outgoing requests' responses:
- A query's
db.query.textis its SQL with each literal replaced by?, sowhere email = 'taylor@laravel.com'exports aswhere email = ?. Placeholders such as$1stay as you wrote them. - An outgoing request's
url.fullleaves out any user name and password, and replaces each query string value withREDACTED, so?token=abcexports as?token=REDACTED. - When one of Laravel's own operations fails, the span records the failure's kind as
error.typeand a short description that holds no data, such asdatabase error 22P02for a value PostgreSQL couldn't cast,redis error WRONGTYPE,HTTP 404,timeout,cache decode failed, orResend rejected the email with HTTP 422. The same description replaces the error's message on a request, command, or job span whose error wraps one of these failures, such as an error you return asfmt.Errorf("charge: %w", err). - A JSON error, which can quote the value it couldn't handle, is recorded as
JSON error, witherror.typeset tojson. That includes a queued job whose payload no longer decodes, a JSON response that can't encode, and anyencoding/jsonerror your own code wraps. - Any other error from your own code keeps its message, such as
the payment gateway timed out, witherror.typeset to_OTHER, because you wrote the message.
The full error still reaches your logs and your error reporting, so you can see exactly what went wrong there.
Laravel's own log lines export only IDs, counts, durations, statuses, names, and errors as their short descriptions to span events, and the log mail and SMS transports' previews of each message stay in your logs alone. Lines that third-party packages log through slog stay in your logs too, since Laravel can't tell what they quote. Lines you log yourself are exported as you write them, as are URL paths, route parameters, and cache keys, so keep secrets out of them.
When a query returns rows (such as with QueryContext), its span stays open until the rows are closed so the span covers the time spent reading them. Redis spans also record the server's address, port, and database number so you can tell which server ran a slow command.
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.
Laravel finds the current span through the context.Context you pass, so a query, cache operation, or outgoing request appears in a trace only when you call it with the context of a request, command, job, or span of your own. Pass r, or the ctx your command or job receives, down to the code that does the work. A new context.Background() carries neither the span nor your application, so its queries appear in no 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 tracing.Start. Your span becomes a child of the active request or command span, and any queries or outgoing requests that you run with the context tracing.Start returns become children of your span.
For example, this function finds a user's most popular posts for a weekly digest email:
package digest
import (
"context"
"go.laravel.com/model"
"go.laravel.com/tracing"
"app/models"
)
func PopularPosts(ctx context.Context, user models.User) ([]models.Post, error) {
ctx, span := tracing.Start(ctx, "PopularPosts", "user.id", user.ID)
defer span.End()
return model.Query[models.Post]().
WhereEq("user_id", user.ID).
WhereGt("votes", 100).
OrderByDesc("votes").
Limit(5).
Get(ctx)
}A span records only the attributes you pass to tracing.Start. You may pass key-value pairs as in slog ("user.id", user.ID), slog.Attr values, or OpenTelemetry attribute.KeyValue values. This span records the user's ID, while sensitive fields like the user's email address stay out of your traces. The returned tracing.Span is an alias for OpenTelemetry's trace.Span, so you may add attributes as the work goes on with span.SetAttributes, or mark the span as failed with span.SetStatus(codes.Error, err.Error()).
Any messages you log with a span's context, at or above your configured log level, are attached to that span as events. Work you run with the task package, and background work you start with r.Background or laravel.Background, stays inside the span that started it.
A long-running command has no span of its own, so Laravel doesn't trace its queries. Inside a long-running command, tracing.Start begins a new trace instead of a child span, so you may start one span for each pass through the work. For example, if your feeds:watch command refreshes your feeds every five minutes, the function it calls on each pass may start a span, and each refresh then appears as a trace of its own:
func refresh(ctx context.Context) error {
ctx, span := tracing.Start(ctx, "feeds:refresh")
defer span.End()
return refreshFeeds(ctx)
}In this example, refreshFeeds stands for your application's own code that fetches each feed and stores its new posts.
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. Each job in a chain continues the trace of the job before it. 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 schedule:work is a long-running command with no span of its own, each task it executes starts its own trace with the task's command linked beneath it. Laravel passes the trace context through the TRACEPARENT and TRACESTATE environment variables, so external programs or shell commands 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 your tracing vendor's Go module or a stdout exporter for local debugging, build your own OpenTelemetry tracer provider. First, add OpenTelemetry's SDK and the exporter to your module:
go get go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/exporters/stdout/stdouttraceThen set your provider as the TracerProvider option in main.go. For example, this provider prints each span to your terminal while you inspect span attributes locally:
package main
import (
"log"
laravel "go.laravel.com"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"app/bootstrap"
)
func main() {
options := bootstrap.Options()
exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
if err != nil {
log.Fatal(err)
}
options.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter))
laravel.Run(options)
}When you set a provider, Laravel uses it instead of the OTEL_* exporter and shuts it down cleanly when your application exits. Setting the provider in main.go rather than bootstrap/app.go keeps your tests from printing spans.
Because main builds your provider before Laravel reads .env, OpenTelemetry's SDK reads variables such as OTEL_SERVICE_NAME and OTEL_TRACES_SAMPLER only from the process's environment, not from your .env file. To name your service in code instead, pass the provider a resource with sdktrace.WithResource.