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

DatadogBridge

注意

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

Enables bidirectional integration between Mastra tracing and Datadog. Creates native dd-trace APM spans in real time so that auto-instrumented operations inside tools and processors are correctly nested under their parent Mastra span. Emits LLM Observability data through dd-trace's pipeline when spans end.

Constructor
Constructor的直接链接

new DatadogBridge(config?: DatadogBridgeConfig)

DatadogBridgeConfig
datadogbridgeconfig的直接链接

interface DatadogBridgeConfig extends BaseExporterConfig {
apiKey?: string
mlApp?: string
site?: string
service?: string
env?: string
agentless?: boolean
integrationsEnabled?: boolean
flushGraceMs?: number
requestContextKeys?: string[]
}

Extends BaseExporterConfig, which includes:

  • logger?: IMastraLogger - Logger instance
  • logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error' - Log level (default: INFO)

Methods
Methods的直接链接

createSpan
createspan的直接链接

createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined

Called by the Mastra observability instance during span construction. Creates a dd-trace APM span eagerly via tracer.startSpan() and returns Mastra-compatible identifiers. The returned IDs are used by Mastra throughout the span's lifetime. The dd-trace span object is stored internally and used for scope activation.

Returns: SpanIds | undefined - { spanId, traceId, parentSpanId }, or undefined if the bridge is disabled.

executeInContext
executeincontext的直接链接

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

Executes an async function within the dd-trace context of a Mastra span. dd-trace auto-instrumented operations running inside the function (HTTP, database, etc.) will be parented to this span.

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

executeInContextSync
executeincontextsync的直接链接

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

Executes a synchronous function within the dd-trace context of a Mastra span.

Returns: T - The result of the function execution.

flush
flush的直接链接

async flush(): Promise<void>

Force-flushes any buffered LLM Observability data to Datadog without shutting down the bridge. Useful in serverless environments where you need to ensure data is exported before the runtime terminates.

The flush is best-effort: dd-trace sends LLM Observability data from a background writer and gives no way to await the request, so flush() waits flushGraceMs (default 2000 ms) after asking dd-trace to flush, then flushes the APM exporter. Each flush that sent new data costs that full wait, so a serverless handler that awaits flush() per request pays it per request. Raise it if spans from short-lived processes are missing in Datadog, or set it to 0 to skip the wait when something else keeps the process alive.

shutdown
shutdown的直接链接

async shutdown(): Promise<void>

Force-finishes any APM spans that weren't properly closed and flushes pending LLM Observability data. It then disables the integration and clears all internal state.

Usage examples
Usage examples的直接链接

Basic Usage
Basic Usage的直接链接

import tracer from 'dd-trace'

tracer.init({
service: process.env.DD_SERVICE || 'my-mastra-app',
env: process.env.DD_ENV || 'production',
})

import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { DatadogBridge } from '@mastra/datadog'

const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-mastra-app',
bridge: new DatadogBridge({
mlApp: process.env.DD_LLMOBS_ML_APP!,
}),
},
},
}),
agents: { myAgent },
})

Agentless Mode (LLM Observability only, no local agent)
Agentless Mode (LLM Observability only, no local agent)的直接链接

If you don't have a local Datadog Agent and only want LLM Observability data, enable agentless mode:

new DatadogBridge({
mlApp: process.env.DD_LLMOBS_ML_APP!,
apiKey: process.env.DD_API_KEY!,
agentless: true,
})

Note: APM data can't be sent in agentless mode. If you only need LLM Observability data without dd-trace APM, the Datadog Exporter is a simpler choice.

With Additional Exporters
With Additional Exporters的直接链接

The bridge can be combined with non-Datadog exporters to send traces to additional destinations:

import { Mastra } from '@mastra/core'
import { Observability, MastraStorageExporter } from '@mastra/observability'
import { DatadogBridge } from '@mastra/datadog'

const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-mastra-app',
bridge: new DatadogBridge({
mlApp: process.env.DD_LLMOBS_ML_APP!,
}),
exporters: [
new MastraStorageExporter(), // Studio access
],
},
},
}),
})
备注

Don't combine DatadogBridge with DatadogExporter in the same configuration. Both emit to LLM Observability and would double-write the same data.

Setup requirements
Setup requirements的直接链接

The DatadogBridge requires dd-trace to be initialized before any other imports so its auto-instrumentation can patch HTTP, database, and framework libraries at load time.

See the DatadogBridge Guide for complete setup instructions, including dd-trace initialization, bundler externals, and agent configuration.

Span mapping
Span mapping的直接链接

Mastra span types are mapped to Datadog LLM Observability span kinds:

Mastra SpanTypeDatadog Kind
AGENT_RUNagent
MODEL_GENERATIONworkflow
MODEL_STEPllm
TOOL_CALLtool
MCP_TOOL_CALLtool
WORKFLOW_RUNworkflow
All other typestask

Tags support
Tags support的直接链接

tracingOptions.tags values become structured LLM Observability annotation tags: key:value entries are split into key/value pairs, and tags without a colon are set to true.

const result = await agent.generate('Hello', {
tracingOptions: {
tags: ['production', 'instance_name:career-scout-api'],
},
})

This produces:

{
"production": true,
"instance_name": "career-scout-api"
}

Environment variables
Environment variables的直接链接

The bridge reads configuration from these environment variables:

VariableDescription
DD_API_KEYDatadog API key (only required for agentless mode)
DD_LLMOBS_ML_APPML application name
DD_SITEDatadog site
DD_ENVEnvironment name
DD_LLMOBS_AGENTLESS_ENABLEDSet to 'true' or '1' to enable agentless mode