> ## Documentation Index
> Fetch the complete documentation index at: https://docs.output.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenTelemetry

> Export every workflow and step run to Jaeger, Honeycomb, Grafana Tempo, or any OTLP backend, and add your own spans under the step that created them

After this page you can send every workflow and step run to the tracing backend your team already uses, and add your own spans that nest under the step that created them.

Set `OUTPUT_OTEL_ENABLED=true` and the worker exports Temporal's OpenTelemetry spans over OTLP: a span for every workflow run, every step call, and every step attempt, with errors and timing. Leave it unset and nothing changes.

This is separate from Output's [tracing](https://docs.output.ai/operations/tracing.md). Trace files record what each step received and returned, the LLM prompts and results, token usage, and cost. OpenTelemetry spans record the shape and timing of a run, in the same backend as the rest of your services, and carry no step inputs or outputs. The two run side by side, so turning one on doesn't affect the other.

## Quick Start

Start your project with `output dev`, then run Jaeger on the same Docker network as the worker:

```bash theme={null}
docker run -d --name jaeger --network output-sdk_main -p 16686:16686 jaegertracing/all-in-one:1.76.0
```

(`output-sdk_main` is the network `output dev` creates. If you set `DOCKER_SERVICE_NAME`, it is `<DOCKER_SERVICE_NAME>_main`.)

Point the worker at it:

```bash .env theme={null}
OUTPUT_OTEL_ENABLED=true
OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318
OTEL_SERVICE_NAME=blog-evaluator-worker
```

Restart `output dev` so the worker picks up the variables. With OpenTelemetry off, the startup log says so:

```text theme={null}
[info] OTEL: OTEL disabled
```

Run a workflow:

```bash theme={null}
npx output workflow run blog_evaluator paulgraham_hwh
```

Open [http://localhost:16686](http://localhost:16686), pick `blog-evaluator-worker` in the service list, and open the trace.

## What Gets Exported

Each workflow run is one trace. A real run looks like this:

```text theme={null}
RunWorkflow:blog_evaluator
├── StartActivity:__internal#getTraceDestinations
│   └── RunActivity:__internal#getTraceDestinations
├── StartActivity:blog_evaluator#fetch_blog_content
│   └── RunActivity:blog_evaluator#fetch_blog_content
└── StartActivity:blog_evaluator#evaluate_signal_to_noise
    └── RunActivity:blog_evaluator#evaluate_signal_to_noise
```

Temporal names the spans, and Output keeps its names:

| Span | What it covers |
| - | - |
| `RunWorkflow:<workflow>` | The whole workflow run, from start to completion or failure. |
| `StartActivity:<workflow>#<step>` | The workflow calling a step or evaluator, until its last attempt ends. Includes the time spent waiting between retries. |
| `RunActivity:<workflow>#<step>` | One attempt of that step on a worker. A step that is retried has one per attempt. |
| `StartChildWorkflow:<child>` | The workflow starting a child workflow. The child's `RunWorkflow` span nests under it, in the same trace. |

Output's internal activities, such as `__internal#getTraceDestinations`, appear alongside your steps.

**Errors.** A failed attempt marks its `RunActivity` span as an error and records the `ApplicationFailure` Temporal built from what your step threw, with its message and type. When the last attempt fails, `StartActivity` records an `ActivityFailure` wrapping it, and so does `RunWorkflow` if the failure ends the run.

**Replays.** Temporal replays workflow code to rebuild its state, for example after a worker restart. Spans are only exported for new work, so a replay doesn't send duplicates.

> [!WARNING]
>
> Every span created in workflow code (`RunWorkflow`, `StartActivity`, `StartChildWorkflow`) carries the full `workflowInfo()` as attributes: the workflow's memo, search attributes, and the result or failure of the previous run. Don't put anything in search attributes that your tracing backend shouldn't store.

## Configuration

Output reads two variables of its own:

| Variable | Default | Effect |
| - | - | - |
| `OUTPUT_OTEL_ENABLED` | `false` | Turns OpenTelemetry on. Accepts `true`, `1` or `on`. |
| `OUTPUT_OTEL_FLUSH_TIMEOUT_MS` | `5000` | Time to export the queued spans on shutdown. See [Delivery and Volume](#delivery-and-volume). |

Everything else is a standard `OTEL_*` variable, read by the OpenTelemetry packages themselves, not by Output. The ones you'll usually set:

| Variable | Default | Effect |
| - | - | - |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | Base URL of your collector or backend. The exporter appends `/v1/traces`. |
| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | - | Full URL for traces, used as is, without `/v1/traces` appended. Overrides `OTEL_EXPORTER_OTLP_ENDPOINT`. |
| `OTEL_EXPORTER_OTLP_HEADERS` | - | Headers sent with every export, as `key=value` pairs separated by commas. Use it for API keys. |
| `OTEL_SERVICE_NAME` | `unknown_service:node` | The service name your backend groups the spans under. |
| `OTEL_RESOURCE_ATTRIBUTES` | - | Extra attributes on every span, such as `deployment.environment.name=production`. |

The exporter also reads `OTEL_EXPORTER_OTLP_TIMEOUT`, `OTEL_EXPORTER_OTLP_COMPRESSION` and the certificate variables, each with a `_TRACES_` variant.

Spans are sent as OTLP over HTTP with protobuf payloads (`http/protobuf`), the protocol the OpenTelemetry specification recommends as the default. gRPC isn't supported, so point the endpoint at the collector's HTTP port (`4318` by default).

### Variables Output Doesn't Honor

The [OpenTelemetry specification](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/) defines more variables than the packages Output uses read. These have no effect:

| Variable | Instead |
| - | - |
| `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | Spans are always sent as `http/protobuf`. JSON and gRPC aren't supported. |
| `OTEL_SDK_DISABLED`, `OTEL_TRACES_EXPORTER` | Use `OUTPUT_OTEL_ENABLED`. |
| `OTEL_PROPAGATORS` | Output always propagates W3C trace context, the only context Temporal carries between workflows and activities. Baggage isn't propagated. |
| `OTEL_LOG_LEVEL` | OpenTelemetry's warnings and errors are always logged, under the `OTEL` namespace. |

To send spans straight to Honeycomb:

```bash .env theme={null}
OUTPUT_OTEL_ENABLED=true
OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io
OTEL_EXPORTER_OTLP_HEADERS=x-honeycomb-team=your-api-key
OTEL_SERVICE_NAME=research-worker
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production
```

## Adding Your Own Spans

You create spans with the OpenTelemetry API, and Output places them in the trace based on where your code runs:

| Where you create the span | Where it lands |
| - | - |
| A step or evaluator | Under that attempt's `RunActivity:<workflow>#<step>` span. |
| `onActivityStart`, `onActivityEnd`, `onActivityError`, and `onError` for a step | Under the step's `RunActivity` span. |
| `on()` listeners, for events emitted while a step runs, such as `http:request` or your own `emit()` calls | Under the span that was active when the event was emitted, usually the step's `RunActivity` span. |
| `onWorkflowStart`, `onWorkflowEnd`, `onWorkflowError`, and `onError` for a workflow or the worker | The root of a new trace. |

Install the OpenTelemetry API in your project:

```bash theme={null}
npm install @opentelemetry/api@~1.9.0
```

> [!WARNING]
>
> Keep `@opentelemetry/api` on `1.9.x`, the version Output sets up the tracer with. A newer minor version can't use that setup and returns a tracer that does nothing, so your spans disappear without an error.

### In Steps

Start spans from a tracer:

```typescript theme={null}
// src/workflows/lead_enrichment/steps.ts
import { step, z } from '@outputai/core';
import { outputFetch } from '@outputai/core/http';
import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('lead-enrichment');

export const lookupCompany = step({
  name: 'lookup_company',
  description: 'Find the company behind a lead email domain',
  inputSchema: z.object({ domain: z.string() }),
  outputSchema: z.object({ name: z.string(), employees: z.number() }),
  fn: async ({ domain }) => tracer.startActiveSpan('company_lookup', async span => {
    span.setAttribute('lead.domain', domain);
    try {
      const response = await outputFetch(`https://company.example.com/v1/companies?domain=${domain}`);
      const company = await response.json();
      span.setAttribute('company.employees', company.employees);
      return { name: company.name, employees: company.employees };
    } finally {
      span.end();
    }
  })
});
```

The trace now shows `company_lookup` under `RunActivity:lead_enrichment#lookup_company`, once per attempt.

The name you pass to `trace.getTracer()`, `lead-enrichment` here, labels the code that created the spans. OpenTelemetry calls it the instrumentation scope, and backends show it on each span (as `otel.scope.name` or the library name), so you can filter by it. It doesn't change where the spans nest or which service they belong to; that's `OTEL_SERVICE_NAME`. Use your project's or module's name.

LLM calls through `@outputai/core/llm` don't emit OpenTelemetry spans. Their prompts, results, token usage, and cost are in Output's [trace files](https://docs.output.ai/operations/tracing.md). If a step calls the AI SDK directly, its `experimental_telemetry` option emits spans that nest under the step like your own.

### In Hooks

[Hooks](https://docs.output.ai/packages/core.md#hooks) that react to a step run inside that step's context, so their spans nest under its `RunActivity` span. They run after the event, so their spans can end after the step's span does, and backends still show them under it:

```typescript theme={null}
// src/hooks/audit_log.ts
import { onActivityEnd, onWorkflowEnd } from '@outputai/core/hooks';
import { trace } from '@opentelemetry/api';
import { writeAuditEntry } from '../clients/audit_log.js';

const tracer = trace.getTracer('audit-log');

onActivityEnd(({ activityInfo, workflowDetails }) => tracer.startActiveSpan('audit_step', async span => {
  try {
    await writeAuditEntry({ workflowId: workflowDetails.workflowId, step: activityInfo.activityType });
  } finally {
    span.end();
  }
}));

onWorkflowEnd(({ workflowDetails }) => tracer.startActiveSpan('audit_workflow', async span => {
  span.setAttribute('temporalWorkflowId', workflowDetails.workflowId);
  try {
    await writeAuditEntry({ workflowId: workflowDetails.workflowId, status: 'completed' });
  } finally {
    span.end();
  }
}));
```

`audit_step` shows up under each step's `RunActivity` span. `audit_workflow` starts its own trace: workflow hooks run on the worker after Temporal processes the workflow's progress, outside any span. To find it next to the workflow's trace, set the workflow ID as `temporalWorkflowId`, the attribute Temporal puts on its `RunActivity` spans, and search your backend by it.

## Output Owns the Tracer Setup

OpenTelemetry has one global tracer provider per process, and the first one registered wins. Output registers its own before it loads your hooks and steps, so leave the setup to Output and only call `trace.getTracer()` in your code.

If something else registers a provider first, such as an APM agent preloaded with `NODE_OPTIONS=--import`, the worker warns at startup:

```text theme={null}
[warn] OTEL: Another tracer provider was registered first, activity spans go to it, workflow spans to the OTLP exporter
```

The trace is then split in two: step spans and your own spans go to that provider, and workflow spans go to the OTLP endpoint. A provider registered after Output's is refused, and OpenTelemetry's error about the duplicate registration shows up in the worker logs. In both cases, remove the other setup.

If your project installs a second copy of `@opentelemetry/api` that Temporal resolves instead of Output's, Temporal can't see Output's setup and step spans are dropped. The worker warns at startup:

```text theme={null}
[warn] OTEL: Temporal uses another @opentelemetry/api copy, which cannot see the tracer provider, so activity spans are dropped
```

Align your project's `@opentelemetry/api` with the version `@outputai/core` depends on, so a single copy is installed.

OpenTelemetry's own warnings and errors are logged under the `OTEL` namespace, at the levels set by `OUTPUT_LOG_LEVEL`.

## Delivery and Volume

Spans are batched in memory and exported every 5 seconds, 512 at a time. The queue holds 2048 spans, and spans that arrive when it is full are dropped. Tune it with the standard variables:

| Variable | Default | Effect |
| - | - | - |
| `OTEL_BSP_SCHEDULE_DELAY` | `5000` | Milliseconds between exports. |
| `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | `512` | Spans per export. |
| `OTEL_BSP_MAX_QUEUE_SIZE` | `2048` | Spans held while waiting for export. |
| `OTEL_BSP_EXPORT_TIMEOUT` | `30000` | Milliseconds before an export is abandoned. |

A failed export is logged as an error under the `OTEL` namespace and its spans are dropped. Workflows and steps keep running, so a collector outage costs spans, not runs.

Leave `OTEL_TRACES_SAMPLER` unset and sample in your collector, where it can keep or drop whole traces. Workflow spans are always recorded, and `OTEL_TRACES_SAMPLER` applies only to step spans:

| Value | Result |
| - | - |
| `parentbased_always_on` (default), `parentbased_traceidratio` | Step spans follow their workflow span, which is always recorded, so every span is exported and the ratio has no effect. |
| `traceidratio` | Step spans are dropped at the ratio while their workflow spans are exported, so traces have gaps. |
| `always_off`, `parentbased_always_off` | Only workflow spans are exported. |

On shutdown, the worker exports the spans still queued, in parallel with the hook flush, for up to `OUTPUT_OTEL_FLUSH_TIMEOUT_MS` (`5000`), whatever the exporter's own timeout. Spans not exported by then are dropped with a warning. Spans that hook callbacks create during the flush aren't included. See [Worker Shutdown](https://docs.output.ai/operations/worker-shutdown.md) for how it fits the shutdown budget.

## Rolling It Out

Turning OpenTelemetry on or off changes the worker's workflow bundle, so its build ID changes too. Output doesn't use Temporal's worker versioning, so the build ID doesn't affect routing.

Workflows already running when you deploy keep running on the new worker. A run started before OpenTelemetry was on exports only the spans for the work done after the switch, so its trace is partial.

## Next Steps

> [card] [Tracing](https://docs.output.ai/operations/tracing.md)
>
> Output's trace files, with step inputs, outputs, LLM calls, and cost.

> [card] [Worker Shutdown](https://docs.output.ai/operations/worker-shutdown.md)
>
> Size the shutdown settings and read the shutdown logs.

> [card] [Deployment](https://docs.output.ai/operations/deployment.md)
>
> Deploy workers to Render, Railway, or your own platform.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.