#OpenTelemetry SDK

This package is the MoonBit SDK facade. It re-exports common API aliases and high-level SDK types from interface/common, interface/context, interface/propagation, sdk/resource, sdk/trace, sdk/logs, and sdk/metrics so application code can configure the usual telemetry pipeline from one import path.

Signal-specific configuration that is not part of the facade still lives in the signal packages. Import sdk/metrics directly for metric views, temporality, streams, and concrete instrument builders. Import sdk/logs directly when configuring log batch options such as BatchConfig.

The API layer answers "where should instrumentation write data?". The SDK layer answers "what should happen to that data?". Applications own the SDK layer: samplers, processors, metric readers, exporters, resources, batching, flushing, and shutdown.

#When To Import This Package

Import moonbit-community/opentelemetry/sdk in applications, test harnesses, and integration packages that configure telemetry. Library instrumentation should normally import the root package or interface/* instead, so the final application remains free to choose whether telemetry is enabled.

#Provider Lifecycle

The lifecycle is the same for all signals:

  1. Build a provider with the signal-specific builder.
  2. Attach exporters, processors, readers, resources, samplers, or views.
  3. Register the provider with sdk.set_*_provider() if application code uses global lookup.
  4. Spawn background tasks for batch processors and periodic metric readers.
  5. Force flush and shut down providers during teardown.

The SDK does not automatically start background export loops. Call spawn_background_tasks(group) after global provider registration when using:

  • BatchSpanProcessor
  • BatchLogProcessor
  • PeriodicMetricReader

#Minimal Trace Setup

///|
async fn _sdk_readme_trace_setup() -> Unit {
let exporter = InMemorySpanExporter::new()
let provider = tracer_provider_builder()
.with_simple_exporter(exporter.into_span_exporter())
.build()

let tracer = provider.tracer("sdk-readme")
let span = tracer.start("startup")
span.end()

ignore(provider.shutdown())
}

To make root-package calls such as @otel.tracer() use this provider, register it with set_tracer_provider(provider). The SDK facade updates both SDK global state and the public API global state.

#Traces

Trace providers own:

  • Config: sampler, ID generator, span limits, and resource
  • SpanProcessor pipeline: on_start, on_end, force_flush, and shutdown
  • SimpleSpanProcessor: exports each ended span immediately
  • BatchSpanProcessor: queues ended spans and exports batches from a background loop
  • SpanExporter: destination-agnostic exporter callback wrapper

Sampling happens when a span starts. Sampler::always_off() still creates a span context for propagation, but the span is not recording and processors do not receive start/end callbacks.

Use simple processors for examples and tests. Use batch processors for production-style network exporters because they reduce request-path export costs.

#Metrics

Metric providers own:

  • synchronous instruments that update in-memory aggregation state
  • observable instruments whose callbacks run during collection
  • ManualReader for pull-style collection in tests or integrations
  • PeriodicMetricReader for scheduled background exports
  • MetricExporter for exporting collected MetricData
  • views that can rename streams, choose aggregation, filter attributes, and set cardinality limits

Metric instruments should be created once and reused. Creating instruments inside hot paths registers extra collectors and increases memory use.

#Logs

Log providers own a processor pipeline similar to tracing:

  • SimpleLogProcessor: exports each log record immediately
  • BatchLogProcessor: queues log records and exports batches from a background loop
  • LogExporter: destination-agnostic exporter callback wrapper

The public logs package provides mutable LogRecord builders. The SDK stores immutable log snapshots that include resource and instrumentation scope before processors receive them.

#Resources

Resource describes the entity producing telemetry. Typical attributes include service name, service version, deployment environment, host, process, or cloud metadata. Resource attributes are attached to exported spans, logs, and metrics.

The default resource builder reads:

  • OTEL_SERVICE_NAME
  • OTEL_RESOURCE_ATTRIBUTES

Prefer setting service.name explicitly for applications so downstream tools can group telemetry correctly.

#Global SDK Helpers

sdk/global keeps process-wide SDK providers and a text-map propagator. The facade helpers in this package delegate to sdk/global:

  • tracer_provider_builder(), logger_provider_builder(), meter_provider_builder()
  • tracer(name, version?, schema_url?, attributes?)
  • logger(name, version?, schema_url?, attributes?)
  • meter(name, version?, schema_url?, attributes?)
  • spawn_background_tasks(group, allow_failure?)

Important distinction: root-package instrumentation uses interface/global, while sdk.tracer(), sdk.logger(), and sdk.meter() use sdk/global. Applications that want library instrumentation to light up should register SDK providers with sdk.set_*_provider(). Those helpers update sdk/global and also install the converted API providers into interface/global. Only call interface/global.set_*_provider() directly when you already have an API-layer provider, for example from provider.into_*_provider().

#Environment Variables

Programmatic builder methods take precedence over environment defaults whenever both are present.

AreaVariableMeaningDefault
ResourceOTEL_SERVICE_NAMESets service.name; takes priority over service.name in OTEL_RESOURCE_ATTRIBUTES.implementation default
ResourceOTEL_RESOURCE_ATTRIBUTESComma-separated key=value resource attributes.none
Trace samplingOTEL_TRACES_SAMPLERalways_on, always_off, traceidratio, parentbased_always_on, parentbased_always_off, or parentbased_traceidratio.parentbased_always_on
Trace samplingOTEL_TRACES_SAMPLER_ARGRatio for ratio-based samplers.1.0
Trace limitsOTEL_SPAN_ATTRIBUTE_COUNT_LIMITMax attributes per span.128
Trace limitsOTEL_SPAN_EVENT_COUNT_LIMITMax events per span.128
Trace limitsOTEL_SPAN_LINK_COUNT_LIMITMax links per span.128
Batch spansOTEL_BSP_SCHEDULE_DELAYDelay between scheduled batch exports, in milliseconds.5000
Batch spansOTEL_BSP_MAX_QUEUE_SIZEMax queued ended spans.2048
Batch spansOTEL_BSP_MAX_EXPORT_BATCH_SIZEMax spans per export batch, capped by queue size.512
Batch spansOTEL_BSP_EXPORT_TIMEOUTExport timeout budget in milliseconds.30000
Batch logsOTEL_BLRP_SCHEDULE_DELAYDelay between scheduled log exports, in milliseconds.1000
Batch logsOTEL_BLRP_MAX_QUEUE_SIZEMax queued log records.2048
Batch logsOTEL_BLRP_MAX_EXPORT_BATCH_SIZEMax log records per export batch, capped by queue size.512
Batch logsOTEL_BLRP_EXPORT_TIMEOUTExport timeout budget in milliseconds.30000
MetricsOTEL_METRIC_EXPORT_INTERVALPeriodic metric export interval, in milliseconds.60000

OTLP exporter variables are documented in ../otlp/README.mbt.md.

#Shutdown Rules

  • Call force_flush() when you need a best-effort export before a known boundary.
  • Call shutdown() exactly once for providers you own during application exit.
  • After shutdown, providers reject or ignore later telemetry work depending on signal-specific behavior.
  • Batch processors and periodic readers need background tasks to export before shutdown; without those tasks, data may only be exported by explicit flush or shutdown.

Aggregation

Aggregated metric payload for one attribute set. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#aggregation

Baggage

SDK baggage map carried through context and propagation. Spec: https://opentelemetry.io/docs/specs/otel/baggage/api/#overview

BaggagePropagator

W3C baggage propagator. Spec: https://opentelemetry.io/docs/specs/otel/baggage/api/#propagation

BatchConfig

Batch span/log processor configuration. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#batching-processor

BatchLogProcessor

Log processor that queues records and exports batches from a background loop. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#batching-processor

BatchSpanProcessor

Span processor that queues ended spans and exports batches from a background loop. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#batching-processor

Config

Trace provider configuration. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer-provider

Context

SDK context carrying span context, baggage, and telemetry suppression. Spec: https://opentelemetry.io/docs/specs/otel/context/#overview

Counter

Monotonic counter instrument. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#counter

CounterBuilder

Builder for monotonic counter instruments. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#instrument

Gauge

Gauge instrument for the latest value of current state. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#gauge

GaugeBuilder

Builder for gauge instruments. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#instrument

Histogram

Histogram instrument for distributions such as latency or payload size. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#histogram

HistogramBuilder

Builder for histogram instruments. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#instrument

HistogramSummary

Compact histogram aggregation summary. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#aggregation

InMemoryLogExporter

Test log exporter that stores emitted logs in memory. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#logrecordexporter

InMemoryMetricExporter

Test metric exporter that stores exported metrics in memory. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk_exporters/in-memory/#metrics-exporter---in-memory

InMemorySpanExporter

Test span exporter that stores finished spans in memory. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#span-exporter

InstrumentKind

Metric instrument kind. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#instrument

InstrumentationScope

Metadata naming the instrumentation library or component producing telemetry. Spec: https://opentelemetry.io/docs/specs/otel/common/instrumentation-scope/

Key

Attribute key type shared by all SDK signals. Spec: https://opentelemetry.io/docs/specs/otel/common/#attribute

KeyValue

One OpenTelemetry attribute key/value pair. Spec: https://opentelemetry.io/docs/specs/otel/common/#attribute

LogExporter

Callback wrapper for exporting log batches. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#logrecordexporter

LogProcessor

Processing hook for emitted log records. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#logrecordprocessor

LogRecord

Immutable SDK log record snapshot. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#additional-logrecord-interfaces

ManualReader

Pull-based metric reader. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#metricreader

MetricData

Immutable metric data item exported by readers. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#metricreader

MetricExporter

Callback wrapper for exporting metric batches. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#metricexporter

Number

Numeric value stored inside metric aggregations. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#aggregation

OTelSdkError

Error type returned by SDK exporters, processors, readers, and providers. Spec: https://opentelemetry.io/docs/specs/otel/error-handling/#basic-error-handling-principles

OTelSdkResult

Standard SDK result alias. Spec: https://opentelemetry.io/docs/specs/otel/error-handling/#basic-error-handling-principles

PeriodicMetricReader

Background metric reader that exports on an interval. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#periodic-exporting-metricreader

Resource

Resource attributes describing the entity that produced telemetry. Spec: https://opentelemetry.io/docs/specs/otel/resource/data-model/#resource-data-model

ResourceBuilder

Builder for resources and resource detector output. Spec: https://opentelemetry.io/docs/specs/otel/resource/sdk/#resource-creation

ResourceDetector

Callback wrapper for detecting resource attributes. Spec: https://opentelemetry.io/docs/specs/otel/resource/sdk/#detecting-resource-information-from-the-environment

Sampler

Sampling policy evaluated when a span starts. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#sampling

SamplingDecision

Sampling decision controlling recording and sampled trace flag. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#sampling

SamplingResult

Sampler output: decision plus attributes and trace state. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#sampling

SdkLogger

SDK logger scoped to one instrumentation library. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#logger

SdkLoggerProvider

SDK logger provider owning resource and log processors. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#loggerprovider

SdkLoggerProviderBuilder

Builder for SDK logger providers. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#loggerprovider

SdkMeter

SDK meter scoped to one instrumentation library. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#meter

SdkMeterProvider

SDK meter provider owning metric instruments, readers, exporters, views, and resource. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#meterprovider

SdkMeterProviderBuilder

Builder for SDK meter providers. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#meterprovider

SdkTracer

SDK tracer scoped to one instrumentation library. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer

SdkTracerProvider

SDK trace provider owning sampler, ID generator, span limits, resource, and processors. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer-provider

SdkTracerProviderBuilder

Builder for SDK trace providers. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer-provider

SeverityNumber

OpenTelemetry log severity number. Spec: https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitynumber

SimpleLogProcessor

Log processor that exports every record immediately. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#simple-processor

SimpleSpanProcessor

Span processor that exports every ended span immediately. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#simple-processor

Span

SDK span handle for one in-flight operation. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#span

SpanContext

Trace/span identity plus flags, remote marker, and trace state. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#spancontext

SpanData

Immutable snapshot of a completed or in-flight span. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#span

SpanEvent

Timestamped span event. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#add-events

SpanExporter

Callback wrapper for exporting finished span batches. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#span-exporter

SpanId

8-byte span identifier. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#spancontext

SpanKind

OpenTelemetry span kind: internal, client, server, producer, or consumer. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#spankind

SpanLimits

Per-span limits for attributes, events, and links. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#span-limits

Relationship from one span to another span context. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#link

SpanProcessor

Processing hook called when spans start and end. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#span-processor

Status

Span status with code and optional description. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#set-status

StatusCode

Span status code. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#set-status

TextMapCompositePropagator

Composite propagator that runs multiple text-map propagators. Spec: https://opentelemetry.io/docs/specs/otel/context/api-propagators/#composite-propagator

TextMapPropagator

Erased text-map propagator used by SDK global state. Spec: https://opentelemetry.io/docs/specs/otel/context/api-propagators/#textmap-propagator

TraceContextPropagator

W3C trace-context propagator for traceparent and tracestate. Spec: https://opentelemetry.io/docs/specs/otel/context/api-propagators/#w3c-trace-context-requirements

TraceFlags

W3C trace flags, including the sampled bit. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#spancontext

TraceId

16-byte trace identifier. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#spancontext

TraceState

W3C trace state container used by trace propagation. Spec: https://opentelemetry.io/docs/specs/otel/trace/api/#tracestate

UpDownCounter

Additive counter instrument for values that can go up or down. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#updowncounter

UpDownCounterBuilder

Builder for up-down counter instruments. Spec: https://opentelemetry.io/docs/specs/otel/metrics/api/#instrument

Value

Attribute value type shared by spans, metrics, logs, and resources. Spec: https://opentelemetry.io/docs/specs/otel/common/#anyvalue

force_flush

async fn force_flush() -> Unit

Flushes all globally registered SDK providers, ignoring individual errors. Specs:
  • https://opentelemetry.io/docs/specs/otel/trace/sdk/#forceflush
  • https://opentelemetry.io/docs/specs/otel/logs/sdk/#forceflush
  • https://opentelemetry.io/docs/specs/otel/metrics/sdk/#forceflush

logger

fn logger(name : StringView, version? : String?, schema_url? : String?, attributes? : ArrayView[
KeyValue
]) ->
SdkLogger

Creates an SDK logger from the current sdk/global logger provider. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#logger-creation

logger_provider_builder

Starts building an SDK logger provider.

Applications use the returned builder to configure resources and log processors/exporters. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#loggerprovider

meter

fn meter(name : StringView, version? : String?, schema_url? : String?, attributes? : ArrayView[
KeyValue
]) ->
SdkMeter

Creates an SDK meter from the current sdk/global meter provider. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#meter

meter_provider_builder

Starts building an SDK meter provider.

Applications use the returned builder to configure resources, readers, exporters, and views. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#meterprovider

set_logger_provider

Registers the global SDK logger provider and updates the public API global. Spec: https://opentelemetry.io/docs/specs/otel/logs/sdk/#loggerprovider

set_meter_provider

Registers the global SDK meter provider and updates the public API global. Spec: https://opentelemetry.io/docs/specs/otel/metrics/sdk/#meterprovider

set_tracer_provider

Registers the global SDK tracer provider and updates the public API global.

Library instrumentation obtained through the root package or interface/global will create spans backed by this SDK provider. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer-provider

shutdown

async fn shutdown() -> Unit

Shuts down all globally registered SDK providers, ignoring individual errors. Specs:
  • https://opentelemetry.io/docs/specs/otel/trace/sdk/#shutdown
  • https://opentelemetry.io/docs/specs/otel/logs/sdk/#shutdown
  • https://opentelemetry.io/docs/specs/otel/metrics/sdk/#shutdown

spawn_background_tasks

fn spawn_background_tasks(group :
TaskGroup
[Unit], allow_failure? : Bool) -> Unit

Spawns all sdk/global background workers needed by batch processors and periodic metric readers.

Call this after registering global SDK providers when using BatchSpanProcessor, BatchLogProcessor, or PeriodicMetricReader. Specs:
  • https://opentelemetry.io/docs/specs/otel/trace/sdk/#batching-processor
  • https://opentelemetry.io/docs/specs/otel/logs/sdk/#batching-processor
  • https://opentelemetry.io/docs/specs/otel/metrics/sdk/#periodic-exporting-metricreader

tracer

fn tracer(name : StringView, version? : String?, schema_url? : String?, attributes? : ArrayView[
KeyValue
]) ->
SdkTracer

Creates an SDK tracer from the current sdk/global tracer provider.

This helper is convenient for application-owned instrumentation. Library instrumentation usually should use the root package or interface/global instead so applications can install public API providers. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer-creation

tracer_provider_builder

Starts building an SDK tracer provider.

Applications use the returned builder to configure samplers, span limits, resources, and span processors/exporters. Spec: https://opentelemetry.io/docs/specs/otel/trace/sdk/#tracer-provider

Source Files