跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

OtelBridge

注意

The OpenTelemetry Bridge is currently experimental. APIs and configuration options may change in future releases.

Enables bidirectional integration between Mastra tracing and OpenTelemetry infrastructure. Creates native OTEL spans for Mastra operations and inherits context from active OTEL spans. Also forwards Mastra log events to the globally-registered OTEL LoggerProvider, emitting each log under the OTEL context of the originating Mastra span so trace-log correlation works automatically.

Constructor
Constructor的直接链接

new OtelBridge(config?: OtelBridgeConfig)

Methods
Methods的直接链接

executeInContext
executeincontext的直接链接

executeInContext<T>(spanId: string, fn: () => Promise<T>): Promise<T>

Executes an async function within the OTEL context of a Mastra span. OTEL-instrumented code running inside the function will have correct parent relationships.

Returns: Promise<T> - The result of the function execution.

executeInContextSync
executeincontextsync的直接链接

executeInContextSync<T>(spanId: string, fn: () => T): T

Executes a synchronous function within the OTEL context of a Mastra span.

Returns: T - The result of the function execution.

onLogEvent
onlogevent的直接链接

async onLogEvent(event: LogEvent): Promise<void>

Forwards a Mastra log event to the globally-registered OTEL LoggerProvider. Trace correlation is resolved in this order:

  1. If the log carries a spanId the bridge has an OTEL span for, the log is emitted under that span's stored OTEL context.
  2. Otherwise, if the log carries traceId and spanId, those IDs are attached to the emitted log record's SpanContext.
  3. Otherwise, the log is emitted under whatever OTEL context is currently active.

If no LoggerProvider is registered globally, emission is a silent no-op.

flush
flush的直接链接

async flush(): Promise<void>

Force flushes the tracer provider and logger provider if they support forceFlush. The global providers are resolved at flush time, so a LoggerProvider registered after the bridge was constructed is flushed too. Useful in serverless environments where you need to drain telemetry before the runtime terminates. Your OTEL SDK may still hold a batch it has already started exporting; call sdk.shutdown() as well before the process exits; the provider's own forceFlush() doesn't wait for that batch either.

shutdown
shutdown的直接链接

async shutdown(): Promise<void>

Shuts down the bridge and cleans up resources. Ends any spans that weren't properly closed, then flushes the providers so those spans are exported.

Usage examples
Usage examples的直接链接

Basic Usage
Basic Usage的直接链接

import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { OtelBridge } from '@mastra/otel-bridge'

const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-service',
bridge: new OtelBridge(),
},
},
}),
agents: { myAgent },
})

Combined with Exporters
Combined with Exporters的直接链接

The bridge can be used alongside exporters. The bridge handles OTEL context, while exporters send data to additional destinations:

import { Mastra } from '@mastra/core'
import { Observability, MastraStorageExporter } from '@mastra/observability'
import { OtelBridge } from '@mastra/otel-bridge'
import { LangfuseExporter } from '@mastra/langfuse'

const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-service',
bridge: new OtelBridge(), // Handles OTEL context
exporters: [
new MastraStorageExporter(), // Studio access
new LangfuseExporter({
// Additional destination
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
secretKey: process.env.LANGFUSE_SECRET_KEY,
}),
],
},
},
}),
})

Setup requirements
Setup requirements的直接链接

The bridge creates spans through an OpenTelemetry tracer provider. For Mastra spans to be exported:

  • A tracer provider must be available. Register one globally before Mastra runs, for example by calling sdk.start() on NodeSDK from @opentelemetry/sdk-node, or by calling trace.setGlobalTracerProvider(provider). If the provider isn't registered globally, pass it with new OtelBridge({ tracerProvider }).
  • A context manager must be installed for Mastra spans to nest under outer spans. NodeSDK installs one automatically. Without a context manager, spans are still exported, but Mastra root spans can't read the active span, so they start new traces instead of joining the outer trace.

When no tracer provider is available, agents and workflows still run, but no Mastra spans are exported through OpenTelemetry. The bridge logs this warning once:

[OtelBridge] No OpenTelemetry tracer provider is registered globally, so Mastra spans will not be exported through OpenTelemetry. ...

See the OtelBridge Guide for complete setup instructions, including how to configure OTEL instrumentation and run your application.

Tags support
Tags support的直接链接

The OtelBridge supports trace tagging for categorization and filtering. Tags are only applied to root spans and are included as the mastra.tags attribute on native OTEL spans.

Usage
Usage的直接链接

const result = await agent.generate('Hello', {
tracingOptions: {
tags: ['production', 'experiment-v2', 'user-request'],
},
})

How Tags Are Stored
How Tags Are Stored的直接链接

Tags are stored as a JSON-stringified array in the mastra.tags span attribute:

{
"mastra.tags": "[\"production\",\"experiment-v2\",\"user-request\"]"
}

The format is compatible with all OTEL-compatible backends and collectors.