AAnvio
Backend

Logging

How Anvio records runtime activity today — plain console output plus OpenTelemetry tracing, and where structured logging is still a gap.

4 min read

Anvio does not have a dedicated structured-logging package (no pino, winston, or custom @anvio/logger). Logging today is two separate things: plain console.* calls for operational messages, and OpenTelemetry spans/metrics via @anvio/observability for tracing and cost data.

There is no unified structured logger across packages. console.log / console.error calls are scattered directly in application code (39+ call sites across packages/*/src at last check, plus apps/*/src/main.ts). If you need log correlation with a specific session or agent run, use OTel span attributes and the audit trail described below, not console output.

Console output

Example from apps/api/src/main.ts:

const port = parseInt(process.env.API_PORT ?? '3000', 10);
await app.listen(port, process.env.API_HOST ?? '0.0.0.0');
console.log(`API listening on port ${port} (auth optional — see workspace/anvio.yaml)`);

The MCP stdio client also forwards a child process's stderr straight to console:

// packages/integrations/src/mcp-stdio-client.ts
this.proc.stderr.on('data', (chunk: Buffer) => {
  const text = chunk.toString('utf-8').trim();
  if (text) {
    console.error(`[mcp-stdio] ${text}`);
  }
});

There is no log-level filtering, no JSON log format, and no LOG_LEVEL environment variable today — output goes wherever the process's stdout/stderr is directed (terminal, container logs, pm2, etc.).

OpenTelemetry tracing (@anvio/observability)

Structured observability comes from packages/observability, built on the official OTel Node SDK:

export function initObservability(options: ObservabilityOptions): NodeSDK | null {
  const enabled =
    options.enabled ??
    (process.env.ANVIO_OTEL_ENABLED === 'true' || !!process.env.OTEL_EXPORTER_OTLP_ENDPOINT);
  if (enabled === false) return null;

  sdk = new NodeSDK({
    resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: options.serviceName }),
    traceExporter: endpoint ? new OTLPTraceExporter({ url: `${endpoint}/v1/traces` }) : undefined,
    instrumentations: [getNodeAutoInstrumentations()],
  });
  sdk.start();
  return sdk;
}

Every app (apps/api, apps/worker, apps/gateway) calls initObservability() at boot with its own serviceName (for example anvio-api) and shutdownObservability() on SIGINT/SIGTERM.

Enable it with either:

ANVIO_OTEL_ENABLED=true
# or simply set an OTLP endpoint — this also enables tracing implicitly
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

withSpan helper

@anvio/observability exports a withSpan wrapper used to trace individual operations (model calls, tool executions, runtime dispatch) with attributes and automatic error status:

import { withSpan } from '@anvio/observability';

await withSpan('model.chat', { provider: 'anthropic', model: 'claude-sonnet-4-20250514' }, async () => {
  return provider.chat(request);
});

On success the span gets SpanStatusCode.OK; on a thrown error it gets SpanStatusCode.ERROR with the error message attached, and the span still .end()s in a finally block.

Metrics registry

packages/observability/src/metrics-registry.ts exposes getMetricsRegistry() for counters/histograms (token usage, tool call counts, latency) that back the Prometheus-style metrics endpoint served by apps/api/src/metrics.controller.ts. See Monitoring for scrape configuration.

Audit trails (structured, but not "logging")

Some subsystems write their own structured JSON records instead of relying on console output or traces:

SubsystemLocationFormat
Code executionworkspace/audit/executions/One record per sandboxed execution, keyed by auditId
Provider routingworkspace/audit/routing.jsonlPROVIDER_SELECTED, PROVIDER_FAILOVER, PROVIDER_EXHAUSTED events, JSON Lines
Session trajectoryanvio session export <id> [--md]Full session transcript export, JSON or Markdown

These are closer to durable audit logs than to application logging — they persist under workspace/ as part of the local-first, file-first design, and survive process restarts.

Langfuse (LLM observability)

For LLM-specific observability (prompts, completions, token cost per call), Anvio integrates with Langfuse rather than building a custom trace viewer — see docs/72-observability-langfuse.md and the importable dashboard at configs/observability/langfuse-dashboard.json.

What to use when

You need to...Use
Print a one-off operational message during boot/shutdownconsole.log / console.error (existing convention)
Trace a specific operation's duration and success/failurewithSpan() from @anvio/observability
Correlate a failure with a specific session/agent/tool callOTel span attributes, or the relevant workspace/audit/* file
Count tokens, tool calls, or latency for dashboardsgetMetricsRegistry() + Prometheus scrape
Review what an agent actually did in a sessionanvio session export <id>

Not yet shipped

A unified structured logger (JSON logs with levels, correlation IDs, and a single configuration surface) does not exist yet. docs/13-observability.md lists "Structured JSON logs" as a goal, but the current implementation is console.* plus OTel traces/metrics — there is no LOG_LEVEL env var or logger package to configure.

Edit on GitHub

Last updated on

On this page