mastra-observability
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Set up and use Mastra observability: tracing with spans for every agent run, model call, tool call, and workflow step, exporters to Mastra Storage, Mastra platform, Langfuse, LangSmith, Braintrust, Datadog, Sentry, PostHog, Arize, Laminar, and any OpenTelemetry backend, sampling, custom spans and metadata, PinoLogger logging with trace correlation, automatic duration, token, and cost metrics, and human feedback. Use this skill whenever the user wants to trace or debug an agent, see token usage or cost, send traces to an APM or LLM observability tool, redact sensitive data from traces, configure logging, or record user ratings. Triggers on @mastra/observability, Observability, MastraStorageExporter, MastraPlatformExporter, SensitiveDataFilter, tracingOptions, createChildSpan, SpanType, OtelExporter, OtelBridge, DatadogBridge, LangfuseExporter, PinoLogger, @mastra/loggers, addFeedback, getMetricAggregate, traceId. Also triggers when the user cannot tell why an agent did something.
- Reads credentials
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 97
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/observability/dist/docs/ and the installed types.
- Very specific: line 160
Traces show in Langfuse but not Studio: Only the external exporter is configured.
- Very specific: line 169
Unbounded metric queries in production: Always pass filters.timestamp.
- Very specific: line 171
Datadog bridge crashes the bundle: Add dd-trace and its native modules to bundler.externals, and import dd-trace before anything else.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Observability
Configure tracing, logs, metrics, and feedback on a Mastra instance, and send them to Studio, Mastra platform, or any external provider.
When to use
- Turning on tracing for agents, workflows, tools, and model calls
- Choosing and configuring exporters (Mastra Storage, Mastra platform, Langfuse, Datadog, OTel, and others)
- Sampling traces, filtering span types, redacting sensitive data
- Adding custom spans, metadata, tags, or trace names
- Joining Mastra traces to an existing OpenTelemetry or Datadog trace
- Configuring
PinoLogger, transports, and trace-correlated logs - Querying token usage, latency, and cost metrics
- Recording user ratings or QA comments against a trace
When NOT to use
- Scoring output quality with scorers (use
mastra-evals) - Datasets and experiments (use
mastra-datasets-experiments) - The Studio Metrics, Traces, and Logs views as UI (use
mastra-studio-editor) - Hosted observability and platform setup (use
mastra-platform) - Querying traces from the CLI (use
mastra-cli-api) - Storage adapters in general (use
mastra-storage) - Debugging a specific error message (use
mastra-troubleshooting)
Required inputs
- Where data should go: Studio only, Mastra platform, an external provider, or several
- Storage backend for the
observabilitydomain (DuckDB local, ClickHouse production, or platform) - Environment: long-running server or serverless (needs
flush()) - Traffic volume and budget (sampling rate, excluded span types)
- Sensitive fields that must never leave the process
- Provider credentials as env vars (see
references/exporters.md)
The framework: one config, four signals
new Observability({ configs }) from @mastra/observability is passed to new Mastra({ observability }). Each named config has a serviceName, exporters, and optional sampling and processors.
| Signal | Source | Needs |
| Traces | Automatic spans for agent runs, model steps, tool calls, workflow steps, memory | An exporter |
| Logs | logger.info() and Mastra internals, tagged with trace_id/span_id | A logger plus observability storage |
| Metrics | Derived from spans: duration, tokens, cost | An analytics store (DuckDB, ClickHouse, PostgresStoreVNext) |
| Feedback | mastra.observability.addFeedback() | Observability storage |
// src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra'
import { LibSQLStore } from '@mastra/libsql'
import { DuckDBStore } from '@mastra/duckdb'
import { MastraCompositeStore } from '@mastra/core/storage'
import { PinoLogger } from '@mastra/loggers'
import { Observability, MastraStorageExporter, MastraPlatformExporter, SensitiveDataFilter } from '@mastra/observability'
export const mastra = new Mastra({
storage: new MastraCompositeStore({
id: 'composite-storage',
default: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }),
domains: { observability: await new DuckDBStore().getStore('observability') },
}),
logger: new PinoLogger({ name: 'Mastra', level: 'info' }),
observability: new Observability({
configs: {
default: {
serviceName: 'mastra',
exporters: [new MastraStorageExporter(), new MastraPlatformExporter()],
spanOutputProcessors: [new SensitiveDataFilter()],
},
},
}),
})MastraPlatformExporter only sends when MASTRA_PLATFORM_ACCESS_TOKEN is set. Keep MastraStorageExporter next to any external exporter so Studio still shows traces.
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/observability/dist/docs/and the installed types. Otherwise fetchhttps://mastra.ai/docs/observability/overview.md,https://mastra.ai/docs/observability/tracing/overview.md, andhttps://mastra.ai/reference/observability/tracing/configuration.md. Trust these over memory. - Install
@mastra/observabilityplus storage (@mastra/libsql @mastra/duckdbfor local) and any exporter package. - Route the observability domain to an analytics-capable store with
MastraCompositeStoreso metrics work. LibSQL, MSSQL, and MongoDB store traces but not metrics. - Add exporters.
MastraStorageExporterfor Studio,MastraPlatformExporterfor hosted, plus the provider fromreferences/exporters.md. Put credentials in env vars. - Protect data.
SensitiveDataFilteris auto-applied (configure with the top-levelsensitiveDataFilter). UsetracingOptions.hideInput/hideOutputper call. - Control volume. Set
sampling(always,never,ratio,custom),excludeSpanTypes,spanFilter, andserializationOptions. - Add context.
requestContextKeysfor user and tenant IDs,environmentonMastra,tracingOptions.tags,metadata,rootSpanName. - Instrument custom work with
context?.tracingContext.currentSpan?.createChildSpan()inside tools and steps. - Configure logging.
PinoLoggerfrom@mastra/loggers. Setlogging.levelon the observability config. UseprettyPrint: falsefor JSON. - Flush in serverless with
await mastra.observability.flush()before the runtime exits. - Verify in Studio (
npx mastra dev, Observability tab) ornpx mastra api trace list.
Deep dive: custom spans and trace context
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const queryTool = createTool({
id: 'query-db',
description: 'Run a read-only query',
inputSchema: z.object({ query: z.string() }),
execute: async (inputData, context) => {
const span = context?.tracingContext.currentSpan?.createChildSpan({
type: 'generic',
name: 'database-query',
input: { query: inputData.query },
requestContext: context?.requestContext, // enables requestContextKeys extraction
})
try {
const rows = await db.query(inputData.query)
span?.end({ output: rows, metadata: { rowsReturned: rows.length } })
return { rows }
} catch (error) {
span?.error({ error })
throw error
}
},
})Per-call options on generate(), stream(), and run.start():
const result = await agent.generate('Hello', {
requestContext,
tracingOptions: {
tags: ['production', 'experiment-v2'],
metadata: { userId: 'user-123' },
traceId: parentTraceId, // join an external trace
parentSpanId: parentSpanId,
hideInput: true,
},
})
console.log(result.traceId) // undefined when sampled out or tracing is offFailure patterns
- Traces show in Langfuse but not Studio. Only the external exporter is configured. Add
new MastraStorageExporter(). - No metrics, cost, or token columns in Studio. The observability domain is on LibSQL, MSSQL, or MongoDB. Route it to DuckDB, ClickHouse, or
PostgresStoreVNext. - Serverless traces missing. The function froze before export. Call
await mastra.observability.flush(). - Using
DefaultExporterorCloudExporterin new code. Both are deprecated aliases. UseMastraStorageExporterandMastraPlatformExporter. - Custom span processor returns
{ ...span }. The copy cannot export and is dropped. Mutate and return the same span, or returnundefinedto drop. - Replacing the redaction list by accident. Passing
sensitiveFieldsreplaces the defaults. Include every default you still need. - Expecting tags on child spans. Tags apply to the root span only.
- Logs missing from observability storage.
logging.levelfilters them (the logging guide says default'warn'). Setlogging: { level: 'info' }. - Invalid external trace IDs. Trace IDs are 1 to 32 hex chars, span IDs 1 to 16. Invalid values are ignored with a logged error.
- Unbounded metric queries in production. Always pass
filters.timestamp. - Feedback dropped.
addFeedback()with onlytraceIdneeds the trace in storage. ConfigureMastraStorageExporter, and checkmastra.observability.addFeedbackexists first. - Datadog bridge crashes the bundle. Add
dd-traceand its native modules tobundler.externals, and importdd-tracebefore anything else.
Output format
A finished observability delivery contains:
observability(andlogger) configured insrc/mastra/index.ts- Storage routing for the
observabilitydomain suited to the environment - Exporter credentials listed in
.env.example, never committed - Sampling, span filtering, and redaction choices stated with reasons
flush()in serverless handlers- Evidence: a trace visible in Studio or the provider, with its
traceId
Reference files
references/api.md-ObservabilityInstanceConfig, sampling,SpanType, span methods,tracingOptions,PinoLogger, metrics and feedback APIs.references/exporters.md- Every exporter and bridge: package, class, constructor, env vars.references/examples.md- Local dev setup, production multi-exporter, OTel bridge, feedback route, metrics query.references/checklist.md- Production observability checklist.
Live docs
- https://mastra.ai/docs/observability/overview
- https://mastra.ai/docs/observability/tracing/overview
- https://mastra.ai/docs/observability/logging
- https://mastra.ai/docs/observability/metrics/overview
- https://mastra.ai/docs/observability/feedback
- https://mastra.ai/reference/observability/tracing/configuration
- https://mastra.ai/reference/observability/tracing/spans
- https://mastra.ai/reference/logging/pino-logger
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

