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

Span filtering

Span filtering controls which spans are exported from an observability config. Use it to reduce noise or lower per-span costs. It can also keep only the spans that matter for a specific exporter or environment.

For a shorter overview of tracing configuration, see Tracing.

Usage example
Usage example的直接链接

The following example demonstrates how to combine excludeSpanTypes and spanFilter in one observability config:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { SpanType } from '@mastra/core/observability'
import { Observability, MastraStorageExporter } from '@mastra/observability'
import { LangfuseExporter } from '@mastra/langfuse'

export const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: 'my-app',
exporters: [new MastraStorageExporter(), new LangfuseExporter()],
excludeSpanTypes: [SpanType.MODEL_CHUNK, SpanType.MODEL_STEP],
spanFilter: span => {
if (span.type === SpanType.TOOL_CALL && span.attributes?.success) {
return false
}

return true
},
},
},
}),
})

Configuration options
Configuration options的直接链接

excludeSpanTypes?:

SpanType[]
Drops spans by type before processors and spanFilter run. Use this for broad, low-overhead filtering.

spanFilter?:

(span: AnyExportedSpan) => boolean
Receives the exported span and returns true to keep it or false to drop it. Use this when filtering depends on attributes, metadata, timing, or entity identifiers.

excludeSpanTypes
excludespantypes的直接链接

Use excludeSpanTypes when you want to suppress whole categories of spans with minimal configuration.

For the current set of supported values, see the SpanType enum.

src/mastra/index.ts
import { SpanType } from '@mastra/core/observability'

excludeSpanTypes: [SpanType.MODEL_CHUNK, SpanType.MODEL_STEP, SpanType.WORKFLOW_SLEEP]

spanFilter
spanfilter的直接链接

When filtering depends on the exported span contents, use spanFilter.

src/mastra/index.ts
import { SpanType } from '@mastra/core/observability'

spanFilter: span => {
if (span.type === SpanType.MODEL_CHUNK) return false
if (span.type === SpanType.TOOL_CALL && span.attributes?.success) return false

return true
}

Additional examples:

src/mastra/index.ts
// Only export spans from production
spanFilter: span => span.metadata?.environment === 'production'

// Exclude spans from a specific entity
spanFilter: span => span.entityId !== 'noisy-agent'

Processing order
Processing order的直接链接

Span filtering happens at export time in this order:

  1. Internal spans are dropped unless includeInternalSpans is true.
  2. excludeSpanTypes removes matching span types.
  3. spanOutputProcessors transform the remaining spans.
  4. spanFilter decides whether to keep the final exported span.

If spanFilter throws an error, Mastra keeps the span and logs the error to avoid silent data loss.