Default exporter

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Mastra Agent SDK documentation on configuring the DefaultExporter to persist traces to local storage for viewing in Studio. Targeted at developers setting up observability for Mastra applications.

Insight

The DefaultExporter persists traces to configured storage backends, making them accessible through Studio. It’s automatically enabled with default observability configuration and requires no external services. Three tracing strategies are available: realtime (processes events immediately, best for development/debugging), batch-with-updates (buffers events with full lifecycle support, 10-100x throughput improvement), and insert-only (only processes completed spans, 70% reduction in database operations, ideal for analytics). The exporter auto-selects the optimal strategy based on storage provider when strategy is set to ‘auto’. Supported storage providers include ClickHouse (insert-only, production high-volume), PostgreSQL/MSSQL/MongoDB/libSQL (batch-with-updates and insert-only, production low-volume or development). Providers without observability support include Convex, DynamoDB, Cloudflare D1, Cloudflare Durable Objects, Upstash, and LanceDB. Batching configuration options include maxBatchSize (default 1000), maxBatchWaitMs (default 5000), and maxBufferSize (default 10000). Error handling includes exponential backoff retry (500ms, 1s, 2s, 4s) with automatic retry for transient failures and batch dropping after 4 failed attempts. The exporter emits structured drop events with reasons ‘unsupported-storage’ and ‘retry-exhausted’ when it cannot persist observability data.

Hành động

To configure DefaultExporter: 1) Ensure a storage backend is configured (LibSQL, PostgreSQL, ClickHouse, etc.). 2) Install Studio for viewing traces locally. 3) Import Observability and DefaultExporter from @mastra/observability. 4) Add to Mastra config with serviceName and exporters array. Basic setup uses LibSQLStore with file-based SQLite. Recommended production setup includes CloudExporter for hosted Studio and SensitiveDataFilter for span output. Configure batching behavior with maxBatchSize, maxBatchWaitMs, and maxBufferSize options. Override strategy selection explicitly with ‘realtime’, ‘batch-with-updates’, or ‘insert-only’. For providers without observability support, use composite storage to route observability data to a supported provider.

Kết quả

Traces are persisted to the configured storage backend and become accessible through Studio at the Observability section, where users can filter, search, and inspect detailed span information. Batch strategies flush when buffer reaches maxBatchSize, maxBatchWaitMs elapses, maxBufferSize approaches, or during shutdown.


Nội dung gốc (Original)

Default exporter

The DefaultExporter persists traces to your configured storage backend, making them accessible through Studio. It’s automatically enabled when using the default observability configuration and requires no external services.

Production Observability: Observability data can quickly overwhelm general-purpose databases in production. For high-traffic applications, route the observability storage domain to ClickHouse through composite storage. See Production Recommendations for details.

Configuration

Prerequisites

  1. Storage Backend: Configure a storage provider (libSQL, PostgreSQL, etc.)
  2. Studio: Install for viewing traces locally

Basic Setup

import { Mastra } from '@mastra/core'
import { Observability, DefaultExporter } from '@mastra/observability'
import { LibSQLStore } from '@mastra/libsql'
 
export const mastra = new Mastra({
  storage: new LibSQLStore({
    id: 'mastra-storage',
    url: 'file:./mastra.db', // Required for trace persistence
  }),
  observability: new Observability({
    configs: {
      local: {
        serviceName: 'my-service',
        exporters: [new DefaultExporter()],
      },
    },
  }),
})

Include DefaultExporter in your observability configuration:

import { Mastra } from '@mastra/core'
import {
  Observability,
  DefaultExporter,
  CloudExporter,
  SensitiveDataFilter,
} from '@mastra/observability'
import { LibSQLStore } from '@mastra/libsql'
 
export const mastra = new Mastra({
  storage: new LibSQLStore({
    id: 'mastra-storage',
    url: 'file:./mastra.db',
  }),
  observability: new Observability({
    configs: {
      default: {
        serviceName: 'mastra',
        exporters: [
          new DefaultExporter(), // Persists traces to storage for Studio
          new CloudExporter(), // Sends observability data to hosted Mastra Studio (requires MASTRA_CLOUD_ACCESS_TOKEN)
        ],
        spanOutputProcessors: [new SensitiveDataFilter()],
      },
    },
  }),
})

Studio

Access your traces through Studio:

  1. Start Studio
  2. Navigate to Observability
  3. Filter and search your local traces
  4. Inspect detailed span information

Tracing strategies

DefaultExporter automatically selects the optimal tracing strategy based on your storage provider. You can also override this selection if needed.

Available Strategies

StrategyDescriptionUse Case
realtimeProcess each event immediatelyDevelopment, debugging, low traffic
batch-with-updatesBuffer events and batch write with full lifecycle supportLow volume Production
insert-onlyOnly process completed spans, ignore updatesHigh volume Production

Strategy Configuration

new DefaultExporter({
  strategy: 'auto', // Default - let storage provider decide
  // or explicitly set:
  // strategy: 'realtime' | 'batch-with-updates' | 'insert-only'
 
  // Batching configuration (applies to both batch-with-updates and insert-only)
  maxBatchSize: 1000, // Max spans per batch
  maxBatchWaitMs: 5000, // Max wait before flushing
  maxBufferSize: 10000, // Max spans to buffer
})

Storage provider support

Different storage providers support different tracing strategies. Some providers support observability for production workloads, while others are intended primarily for local development.

If you set the strategy to 'auto', the DefaultExporter automatically selects the optimal strategy for the storage provider. If you set the strategy to a mode that the storage provider doesn’t support, you will get an error message.

Providers with Observability Support

Storage ProviderPreferred StrategySupported StrategiesRecommended Use
ClickHouseinsert-onlyinsert-onlyProduction (high-volume)
PostgreSQLbatch-with-updatesbatch-with-updates, insert-onlyProduction (low volume)
MSSQLbatch-with-updatesbatch-with-updates, insert-onlyProduction (low volume)
MongoDBbatch-with-updatesbatch-with-updates, insert-onlyProduction (low volume)
libSQLbatch-with-updatesbatch-with-updates, insert-onlyDefault storage, good for development

Providers without Observability Support

The following storage providers don’t support the observability domain. If you’re using one of these providers and need observability, use composite storage to route observability data to a supported provider:

Strategy Benefits

  • realtime: Immediate visibility, best for debugging
  • batch-with-updates: 10-100x throughput improvement, full span lifecycle
  • insert-only: Additional 70% reduction in database operations, perfect for analytics

Production recommendations

Observability data grows quickly in production environments. A single agent interaction can generate hundreds of spans, and high-traffic applications can produce thousands of traces per day. Most general-purpose databases aren’t optimized for this write-heavy, append-only workload.

ClickHouse is a columnar database designed for high-volume analytics workloads. It’s the recommended choice for production observability because:

  • Optimized for writes: Handles millions of inserts per second
  • Efficient compression: Reduces storage costs for trace data
  • Fast queries: Columnar storage enables quick trace lookups and aggregations
  • Time-series native: Built-in support for time-based data retention and partitioning

Using Composite Storage

If you’re using a provider without observability support (like Convex or DynamoDB) or want to optimize performance, use composite storage to route observability data to ClickHouse while keeping other data in your primary database.

Batching behavior

Flush Triggers

For both batch strategies (batch-with-updates and insert-only), traces are flushed to storage when any of these conditions are met:

  1. Size trigger: Buffer reaches maxBatchSize spans
  2. Time trigger: maxBatchWaitMs elapsed since first event
  3. Emergency flush: Buffer approaches maxBufferSize limit
  4. Shutdown: Force flush all pending events

Error handling

The DefaultExporter includes robust error handling for production use:

  • Retry Logic: Exponential backoff (500ms, 1s, 2s, 4s)
  • Transient Failures: Automatic retry with backoff
  • Persistent Failures: Drop batch after 4 failed attempts
  • Buffer Overflow: Prevent memory issues during storage outages

Dropped observability events

DefaultExporter emits structured drop events when it cannot persist observability data. Register an exporter or bridge with onDroppedEvent to forward these drops to alerting or monitoring.

There are two drop reasons:

  • unsupported-storage: The storage provider does not implement the signal type.
  • retry-exhausted: The exporter retried a batch up to maxRetries times and then dropped it.

The following example demonstrates forwarding drop details to a monitoring endpoint:

import { BaseExporter } from '@mastra/observability'
import type { ObservabilityDropEvent, TracingEvent } from '@mastra/core/observability'
 
class DropAlertExporter extends BaseExporter {
  name = 'drop-alerts'
 
  async onDroppedEvent(event: ObservabilityDropEvent) {
    await fetch('https://monitoring.example.com/observability-drops', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        count: event.count,
        signal: event.signal,
        reason: event.reason,
        exporterName: event.exporterName,
      }),
    })
  }
 
  protected async _exportTracingEvent(_event: TracingEvent) {}
}

Configuration examples

// Zero config - recommended for most users
new DefaultExporter()
 
// Development override
new DefaultExporter({
  strategy: 'realtime', // Immediate visibility for debugging
})
 
// High-throughput production
new DefaultExporter({
  maxBatchSize: 2000, // Larger batches
  maxBatchWaitMs: 10000, // Wait longer to fill batches
  maxBufferSize: 50000, // Handle longer outages
})
 
// Low-latency production
new DefaultExporter({
  maxBatchSize: 100, // Smaller batches
  maxBatchWaitMs: 1000, // Flush quickly
})

Liên kết

Xem thêm: