OpenTelemetry Bridge Integration
Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference
Published: 2026-05-10 · Source: crawler_authoritative
Tình huống
Technical guide for integrating Mastra’s tracing system with existing OpenTelemetry infrastructure, targeting developers building distributed systems who have existing OTEL instrumentation.
Insight
The OpenTelemetry (OTEL) Bridge enables bidirectional integration between Mastra’s tracing system and existing OpenTelemetry infrastructure. Unlike exporters, the bridge creates native OTEL spans that participate in distributed tracing context. From OTEL to Mastra: reads from OTEL ambient context (AsyncLocalStorage), inherits trace ID and parent span ID, respects OTEL sampling decisions, and requires no manual trace ID passing when OTEL auto-instrumentation is active. From Mastra to OTEL: creates native OTEL spans for Mastra operations (agents, LLM calls, tools, workflows), maintains proper parent-child relationships in distributed traces, and forwards Mastra log events to the globally registered OTEL LoggerProvider. Logs originating inside a Mastra span are emitted under that span’s OTEL context for backend correlation. If no LoggerProvider is registered, log emission is a silent no-op. The bridge exports spans using OpenTelemetry Semantic Conventions for GenAI v1.38.0, including standardized span names like ‘chat {model}’ and ‘execute_tool {tool_name}’, and attributes like ‘gen_ai.usage.input_tokens’ and ‘gen_ai.request.model’. Required packages include @mastra/otel-bridge, @opentelemetry/sdk-node, @opentelemetry/auto-instrumentations-node, and OTLP exporters (protobuf, JSON, or gRPC variants).
Hành động
Install the bridge package using npm install @mastra/otel-bridge (pnpm/yarn/bun alternatives available). Create an instrumentation file that initializes the OTEL NodeSDK with serviceName, BatchSpanProcessor with OTLPTraceExporter, getNodeAutoInstrumentations(), and W3CTraceContextPropagator. This instrumentation file must load before application code. Add OtelBridge to Mastra observability config under configs.default.bridge. No Mastra exporters are required. For log forwarding, add BatchLogRecordProcessor with OTLPLogExporter to NodeSDK configuration. Run application with —import flag: ‘tsx —import ./instrumentation.ts ./src/index.ts’. Add tags to agent/workflow execution via tracingOptions parameter to categorize traces in OTEL backend.
Kết quả
Mastra operations appear as native child spans under existing OTEL traces. Traces propagate across service boundaries automatically when services use W3C Trace Context propagator. Logs from within Mastra spans are correlated with traces in backends like Datadog, Grafana, and Honeycomb.
Điều kiện áp dụng
The OpenTelemetry Bridge is experimental — APIs and configuration options may change in future releases. Requires existing OTEL instrumentation in the application. For users without existing OTEL infrastructure, the simpler OpenTelemetry Exporter may be more appropriate.
Nội dung gốc (Original)
OpenTelemetry bridge
Warning: The OpenTelemetry Bridge is currently experimental. APIs and configuration options may change in future releases.
The OpenTelemetry (OTEL) Bridge enables bidirectional integration between Mastra’s tracing system and existing OpenTelemetry infrastructure. Unlike exporters that send trace data to external platforms, the bridge creates native OTEL spans that participate in your distributed tracing context.
Looking to send traces without existing OTEL infrastructure?: If you don’t have existing OpenTelemetry instrumentation, the OpenTelemetry Exporter may be simpler — it sends traces directly without requiring an OTEL SDK setup.
When to use the bridge
Use the OtelBridge when you:
- Have existing OTEL instrumentation in your application (HTTP servers, database clients, etc.)
- Want Mastra operations to appear as child spans of your existing OTEL traces
- Need OTEL-instrumented code inside Mastra tools to maintain proper parent-child relationships
- Are building a distributed system where trace context must propagate across services
How it works
The OtelBridge provides two-way integration:
From OTEL to Mastra:
- Reads from OTEL ambient context (AsyncLocalStorage) automatically
- Inherits trace ID and parent span ID from active OTEL spans
- Respects OTEL sampling decisions — if a trace isn’t sampled, Mastra won’t create spans for it
- No manual trace ID passing required when OTEL auto-instrumentation is active
From Mastra to OTEL:
- Creates native OTEL spans for Mastra operations (agents, LLM calls, tools, workflows)
- Maintains proper parent-child relationships in distributed traces
- Allows OTEL-instrumented code (HTTP clients, database calls) within Mastra operations to nest correctly
- Forwards Mastra log events to the globally-registered OTEL
LoggerProvider. Logs that originate inside a Mastra span are emitted under that span’s OTEL context so backends correlate them with the trace. If noLoggerProvideris registered, log emission is a silent no-op.
Installation
npm:
npm install @mastra/otel-bridgepnpm:
pnpm add @mastra/otel-bridgeYarn:
yarn add @mastra/otel-bridgeBun:
bun add @mastra/otel-bridgeThe bridge works with your existing OpenTelemetry setup. Depending on your configuration, you may also need some of these packages:
@opentelemetry/sdk-node- Core Node.js SDK for OTEL@opentelemetry/auto-instrumentations-node- Auto-instrumentation for common libraries@opentelemetry/exporter-trace-otlp-proto- OTLP exporter (Protobuf over HTTP)@opentelemetry/exporter-trace-otlp-http- OTLP exporter (JSON over HTTP)@opentelemetry/exporter-trace-otlp-grpc- OTLP exporter (gRPC)@opentelemetry/sdk-trace-base- Base tracing SDK (for BatchSpanProcessor, etc.)@opentelemetry/core- Core utilities (for W3CTraceContextPropagator, etc.)@opentelemetry/sdk-logsand an OTLP log exporter (e.g.@opentelemetry/exporter-logs-otlp-http) - Required if you want the bridge to forward Mastra log events too
Configuration
Using the OtelBridge requires two steps:
- Configure OpenTelemetry instrumentation in your application
- Add the OtelBridge to your Mastra observability config
Step 1: OpenTelemetry Instrumentation
Create an instrumentation file that initializes OTEL. This must run before your application code:
import { NodeSDK } from '@opentelemetry/sdk-node'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { W3CTraceContextPropagator } from '@opentelemetry/core'
const sdk = new NodeSDK({
serviceName: 'my-service',
spanProcessors: [
new BatchSpanProcessor(
new OTLPTraceExporter({
url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
}),
),
],
instrumentations: [getNodeAutoInstrumentations()],
textMapPropagator: new W3CTraceContextPropagator(),
})
sdk.start()
export { sdk }Step 2: Mastra Configuration
Add the OtelBridge to your Mastra observability config:
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { OtelBridge } from '@mastra/otel-bridge'
export const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-service',
bridge: new OtelBridge(),
},
},
}),
agents: {
/* your agents */
},
})No Mastra exporters are required when using the bridge — traces are sent via your OTEL SDK configuration. You can optionally add Mastra exporters if you want to send traces to additional destinations.
Forwarding logs (optional)
The bridge also forwards Mastra log events to the globally-registered OTEL LoggerProvider. To wire up logs alongside traces, register a logRecordProcessor on NodeSDK:
import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'
import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'
const sdk = new NodeSDK({
// ...trace config as usual
logRecordProcessor: new BatchLogRecordProcessor(
new OTLPLogExporter({
url: process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT || 'http://localhost:4318/v1/logs',
}),
),
})Logs that originate inside a Mastra span are emitted under that span’s OTEL context, so backends like Datadog, Grafana, and Honeycomb correlate them with the surrounding trace automatically. Logs without trace context fall through to the currently active OTEL context.
If you do not register a LoggerProvider, log emission is a silent no-op — traces continue to work as configured.
Running Your Application
Use the --import flag to ensure instrumentation loads before your application:
tsx --import ./instrumentation.ts ./src/index.tsSemantic conventions
The OtelBridge exports Mastra spans using OpenTelemetry Semantic Conventions for GenAI v1.38.0. This includes standardized span names (chat {model}, execute_tool {tool_name}, etc.) and attributes (gen_ai.usage.input_tokens, gen_ai.request.model, etc.).
For details on span naming and attributes, see the OpenTelemetry Exporter semantic conventions.
Trace hierarchy
With the OtelBridge, your traces maintain proper hierarchy across OTEL and Mastra boundaries:
HTTP POST /api/chat (from Hono middleware)
└── agent.assistant (from Mastra via OtelBridge)
├── chat gpt-5.4 (LLM call)
├── tool.execute search (tool execution)
│ └── HTTP GET api.example.com (from OTEL auto-instrumentation)
└── chat gpt-5.4 (follow-up LLM call)Multi-service distributed tracing
The OtelBridge enables trace propagation across service boundaries. When Service A calls Service B via HTTP, trace context propagates automatically:
Service A: HTTP POST /api/process
└── HTTP POST service-b/api/analyze (outgoing call)
Service B: HTTP POST /api/analyze (incoming call - same trace!)
└── agent.analyzer (Mastra agent inherits trace context)
└── chat gpt-5.4Both services must have:
- OTEL instrumentation configured
- W3C Trace Context propagator enabled
- Mastra with OtelBridge configured
Using tags
Tags help you categorize and filter traces in your OTEL backend. Add tags when executing agents or workflows:
const result = await agent.generate('Hello', {
tracingOptions: {
tags: ['production', 'experiment-v2', 'user-request'],
},
})Tags are exported as a JSON string in the mastra.tags span attribute for broad backend compatibility. Common use cases include:
- Environment labels:
"production","staging" - Experiment tracking:
"experiment-v1","control-group" - Priority levels:
"priority-high","batch-job"
Troubleshooting
If traces aren’t displaying or connecting as expected:
- Verify OTEL SDK is initialized before Mastra (use
--importflag or import at top of entry point) - Ensure the OtelBridge is added to your observability config
- Check that your OTEL backend is running and accessible
Related
- Tracing Overview
- OpenTelemetry Exporter: For sending traces to OTEL backends
- OtelBridge Reference: API documentation
Liên kết
- Nền tảng: Dev Framework · Mastra
- Nguồn: https://mastra.ai/docs/observability/tracing/bridges/otel
Xem thêm: