Creating spans
Use theTracer facade to create custom spans. newSpan returns a SpanBuilder you can configure before starting the span.
Using measure
The simplest approach wraps a callback. The span is automatically activated (so it becomes the parent for any nested spans), and it ends when the callback returns — even if an exception is thrown.
SpanInterface instance is passed to the callback, so you can add attributes or record events:
Manual span management
For finer control, start and end the span yourself:With
start, the span is not automatically set as the active span. Child spans created inside the same block will not see it as their parent unless you activate it (see below).Activating a span
To make a manually started span the active span (so nested spans inherit it as parent), activate it with a scope:Configuring spans
TheSpanBuilder returned by newSpan exposes several builder methods before you call start or measure:
| Method | Description |
|---|---|
setAttribute(string $key, mixed $value) | Set a single attribute on the span |
setAttributes(iterable $attributes) | Set multiple attributes at once |
setParent(?ContextInterface $context) | Override the parent context |
setSpanKind(int $spanKind) | Set the span kind (e.g. SpanKind::KIND_CLIENT) |
setStartTimestamp(CarbonInterface|int $timestamp) | Set a custom start timestamp |
addLink(SpanContextInterface $context, iterable $attributes) | Link to another span |
Tracer facade reference
TheTracer facade provides utility methods for working with the active trace context:
Distributed tracing across services
When calling an external service, inject the current trace context into the outgoing request headers so the downstream service can continue the same trace.The HTTP server and HTTP client instrumentations propagate trace context automatically. Manual propagation is only needed when using custom transports or non-Laravel HTTP clients.
Log context
When a trace is active, the current trace ID can be automatically injected into log records so you can correlate logs with traces in your observability backend.- Automatic: When using the built-in instrumentations (e.g. HTTP server), the trace ID is injected into the log context for the duration of the request.
- Manual: When you start a root span manually, call
Tracer::updateLogContext()after activating the span to inject the trace ID.
config/opentelemetry.php:
| Option | Default | Description |
|---|---|---|
logs.inject_trace_id | true | Enable trace ID injection into the log context |
logs.trace_id_field | trace_id | The field name used in the log context |
When you use the
otlp log channel, the trace ID is always included in exported log records automatically — you do not need to call updateLogContext().