tracing

    Structured tracing with explicit context propagation.

    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    17 days ago
    Downloads
    179

    #moonbit-community/tracing

    Structured tracing for MoonBit with explicit context propagation.

    Tracing state lives in normal values. Create a root TraceContext, pass it to the work that needs tracing, and keep async task relationships and handoffs explicit.

    The repository exposes four packages:

    • moonbit-community/tracing: core tracing types, filtering, dispatch, spans, events, and async propagation helpers.
    • moonbit-community/tracing/jsonl: a ready-made backend that writes records as JSON Lines.
    • moonbit-community/tracing/logfmt: a ready-made backend that writes records as logfmt.
    • moonbit-community/tracing/otel: a bridge that exports tracing spans through an OpenTelemetry trace Tracer.

    Every MoonBit block below uses mbt check. The examples participate in mooncheck and moon test.

    #Shared Helpers

    The examples reuse one small in-memory subscriber.

    ///|
    struct ReadmeCapture {
    starts : Array[@tracing.SpanStart]
    records : Array[@tracing.SpanRecord]
    events : Array[@tracing.EventRecord]
    ends : Array[@tracing.SpanEnd]
    links : Array[@tracing.SpanLink]
    }

    ///|
    fn ReadmeCapture::new() -> ReadmeCapture {
    { starts: [], records: [], events: [], ends: [], links: [], }
    }

    ///|
    fn readme_root_ctx(dispatch : @tracing.Dispatch) -> @tracing.TraceContext {
    @tracing.TraceContext::root(
    dispatch,
    @tracing.TraceIdAllocator::new_seeded(0UL),
    )
    }

    ///|
    fn readme_source_loc(repr : String) -> SourceLoc = "%identity"

    ///|
    fn ReadmeCapture::start_named(
    self : ReadmeCapture,
    name : String,
    ) -> @tracing.SpanStart {
    for start in self.starts {
    if start.metadata.name == name {
    return start
    }
    }
    abort("missing span start: \{name}")
    }

    ///|
    struct ReadmeSink {
    writes : Ref[Int32]
    }

    ///|
    fn ReadmeSink::new() -> ReadmeSink {
    { writes: Ref(0), }
    }

    ///|
    impl @tracing.Subscriber for ReadmeCapture with fn on_span_start(self, record) {
    self.starts.push(record)
    }

    ///|
    impl @tracing.Subscriber for ReadmeCapture with fn on_span_record(self, record) {
    self.records.push(record)
    }

    ///|
    impl @tracing.Subscriber for ReadmeCapture with fn on_event(self, record) {
    self.events.push(record)
    }

    ///|
    impl @tracing.Subscriber for ReadmeCapture with fn on_span_end(self, record) {
    self.ends.push(record)
    }

    ///|
    impl @tracing.Subscriber for ReadmeCapture with fn on_span_link(self, record) {
    self.links.push(record)
    }

    ///|
    impl @io.Writer for ReadmeSink with fn write_once(self, _buf, offset~, len~) {
    ignore(offset)
    self.writes.val += 1
    len
    }

    #Quick Start

    For useful output immediately, start with the jsonl package. with_json_writer creates a root context, writes events and spans as JSON Lines, and shuts the runtime down before the scope exits.

    ///|
    async test "quick start with json writer" {
    let sink = ReadmeSink::new()
    @jsonl.with_json_writer(sink, ctx => {
    ctx.event(Info, "app_started", message="booting", fields=[
    @tracing.field("version", "0.1.0"),
    @tracing.field("port", 3000),
    ])
    ctx.with_span(
    Info,
    "handle_request",
    request_ctx => {
    request_ctx.event(Info, "validated", fields=[
    @tracing.field("method", "GET"),
    @tracing.field("path", "/health"),
    ])
    },
    target="http.server",
    fields=[@tracing.field("request_id", "req-1")],
    )
    })
    // A write confirms that the helper created a root context, delivered records,
    // and flushed on exit.
    assert_true(sink.writes.val > 0)
    }

    #Root Traces

    Create a root context with TraceContext::root(dispatch, trace_ids). Trace ids are allocated lazily. Filtered-out callsites leave the allocator unchanged. Deterministic allocators created with TraceIdAllocator::new_seeded reject the maximum Int64 seed because the first allocation increments the seed before materializing an id.

    ///|
    test "root traces allocate ids lazily" {
    let capture = ReadmeCapture::new()
    let ids = @tracing.TraceIdAllocator::new_seeded(0UL)
    let first = @tracing.TraceContext::root(
    @tracing.Dispatch::from_subscriber(capture),
    ids,
    )
    let second = @tracing.TraceContext::root(
    @tracing.Dispatch::from_subscriber(capture),
    ids,
    )
    first.event(
    Info,
    "first",
    target="readme.root",
    loc=readme_source_loc("root-first"),
    )
    second.event(
    Info,
    "second",
    target="readme.root",
    loc=readme_source_loc("root-second"),
    )
    // The two roots share one allocator. Each root gets an id when it emits its
    // first enabled record.
    debug_inspect(
    capture.events,
    content=(
    #|[
    #| {
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "first",
    #| target: "readme.root",
    #| loc: <SourceLoc: "root-first">,
    #| },
    #| trace_id: 00000000000000000000000000000001,
    #| span: None,
    #| message: None,
    #| fields: [],
    #| },
    #| {
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "second",
    #| target: "readme.root",
    #| loc: <SourceLoc: "root-second">,
    #| },
    #| trace_id: 00000000000000000000000000000002,
    #| span: None,
    #| message: None,
    #| fields: [],
    #| },
    #|]
    ),
    )
    }

    #Events, Fields, and Values

    Events are point-in-time records. Fields carry structured values with stable names and machine-readable payloads.

    field(name, value) accepts any type that implements IntoValue. Built-in implementations cover common scalars, bytes, arrays of Value, and Value itself.

    @tracing.Object preserves insertion order, and each object field name must be unique.

    ///|
    struct ReadmeUser {
    id : Int32
    name : String
    }

    ///|
    impl @tracing.IntoValue for ReadmeUser with fn into_value(self) {
    Object([("id", Int(self.id)), ("name", String(self.name))])
    }

    ///|
    test "fields accept custom values" {
    let user = ReadmeUser::{ id: 7, name: "alice", }
    // Check the exact JSON shape first, then verify that `field(...)` uses the
    // same `IntoValue` conversion automatically.
    let payload = @tracing.Object([
    ("ok", Bool(true)),
    ("user", @tracing.IntoValue::into_value(user)),
    ])
    @debug.assert_eq(
    "{\"ok\":true,\"user\":{\"id\":7,\"name\":\"alice\"}}",
    payload.to_json_string(),
    )
    let field = @tracing.field("user", user)
    assert_true(field.value is Object(_))
    }

    #Scoped Spans

    Use TraceContext::with_span for the common case. It starts a span, passes a child context into the callback, and closes the span automatically.

    ///|
    async test "with_span creates a child context and closes automatically" {
    let capture = ReadmeCapture::new()
    let ctx = readme_root_ctx(@tracing.Dispatch::from_subscriber(capture))
    ignore(
    ctx.with_span(
    Info,
    "handle_request",
    request_ctx => {
    request_ctx.event(
    Info,
    "validated",
    fields=[
    @tracing.field("method", "GET"),
    @tracing.field("path", "/health"),
    ],
    target="http.server",
    loc=readme_source_loc("validated"),
    )
    },
    target="http.server",
    fields=[@tracing.field("request_id", "req-1")],
    loc=readme_source_loc("handle-request"),
    ),
    )
    // The start record shows the new child span and the fields attached when it
    // was opened.
    debug_inspect(
    capture.starts[0],
    content=(
    #|{
    #| metadata: {
    #| kind: Span,
    #| level: Info,
    #| name: "handle_request",
    #| target: "http.server",
    #| loc: <SourceLoc: "handle-request">,
    #| },
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| parent: None,
    #| fields: [{ name: "request_id", value: "req-1" }],
    #|}
    ),
    )
    // The nested event keeps the same trace id and points at the span created by
    // `with_span`. The callback ran inside that scope.
    debug_inspect(
    capture.events[0],
    content=(
    #|{
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "validated",
    #| target: "http.server",
    #| loc: <SourceLoc: "validated">,
    #| },
    #| trace_id: 00000000000000000000000000000001,
    #| span: Some(
    #| {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| ),
    #| message: None,
    #| fields: [{ name: "method", value: "GET" }, { name: "path", value: "/health" }],
    #|}
    ),
    )
    // A successful callback produces one matching `SpanEnd` with status `Ok`.
    // `with_span` closes the span.
    debug_inspect(
    capture.ends[0],
    content=(
    #|{
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| status: Ok,
    #| error: None,
    #|}
    ),
    )
    }

    #Manual Span Lifecycle

    For direct lifecycle control, call TraceContext::span. It returns a SpanHandle and the child context for work inside the span.

    SpanHandle lets you:

    • record(fields) to attach extra fields later
    • follows_from(cause) to add a causal link
    • close(status, error) to end the span exactly once

    ///|
    test "manual span handles support record link and close" {
    let capture = ReadmeCapture::new()
    let ctx = readme_root_ctx(@tracing.Dispatch::from_subscriber(capture))

    let (cause_handle, cause_ctx) = ctx.span(
    Info,
    "cache_lookup",
    target="db",
    loc=readme_source_loc("cache-lookup"),
    )
    // An earlier sibling span can be referenced through `follows_from` as a
    // causal predecessor.
    let cause = cause_ctx.current_span().unwrap()
    ignore(cause_handle.close())

    let (handle, child_ctx) = ctx.span(
    Info,
    "db_query",
    target="db",
    loc=readme_source_loc("db-query"),
    )
    child_ctx.event(
    Info,
    "sql_built",
    target="db",
    loc=readme_source_loc("sql-built"),
    )
    // These calls are the reason to use the manual API: enrich the span after it
    // started, attach a causal link, and choose the final status explicitly.
    assert_true(handle.record([@tracing.field("rows", 3)]))
    assert_true(handle.follows_from(cause))
    assert_true(handle.close(status=Error, error="timeout"))

    // The starts prove both spans belong to the same trace. They are sibling
    // spans in that trace tree.
    debug_inspect(
    capture.starts,
    content=(
    #|[
    #| {
    #| metadata: {
    #| kind: Span,
    #| level: Info,
    #| name: "cache_lookup",
    #| target: "db",
    #| loc: <SourceLoc: "cache-lookup">,
    #| },
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| parent: None,
    #| fields: [],
    #| },
    #| {
    #| metadata: {
    #| kind: Span,
    #| level: Info,
    #| name: "db_query",
    #| target: "db",
    #| loc: <SourceLoc: "db-query">,
    #| },
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000002,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| parent: None,
    #| fields: [],
    #| },
    #|]
    ),
    )
    // Late fields are emitted as a separate `SpanRecord`. The original
    // `SpanStart` stays unchanged.
    debug_inspect(
    capture.records[0],
    content=(
    #|{
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000002,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| fields: [{ name: "rows", value: 3 }],
    #|}
    ),
    )
    // `follows_from` records causality and leaves the parent field unchanged.
    debug_inspect(
    capture.links[0],
    content=(
    #|{
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000002,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| follows_from: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #|}
    ),
    )
    // The final close controls both the terminal status and the optional error
    // text that subscribers observe.
    debug_inspect(
    capture.ends,
    content=(
    #|[
    #| {
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| status: Ok,
    #| error: None,
    #| },
    #| {
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000002,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| status: Error,
    #| error: Some("timeout"),
    #| },
    #|]
    ),
    )
    }

    #Filtering and Fanout

    Dispatch decides which callsites are enabled and where records go.

    • Dispatch::from_subscriber(subscriber) creates one lane
    • Dispatch::fanout([...]) combines multiple lanes
    • dispatch.filtered(filter) applies metadata filtering

    The available filters are:

    • LevelFilter(level)
    • TargetFilter(Map[String, Level])
    • AndFilter(lhs, rhs)

    ///|
    test "fanout filters lanes independently" {
    let left = ReadmeCapture::new()
    let right = ReadmeCapture::new()
    // The left lane is unfiltered. The right lane keeps records whose target
    // matches `http.server`.
    let dispatch = @tracing.Dispatch::fanout([
    @tracing.Dispatch::from_subscriber(left),
    @tracing.Dispatch::from_subscriber(right).filtered(
    TargetFilter({ "http.server": Info }),
    ),
    ])
    let ctx = readme_root_ctx(dispatch)
    ctx.event(
    Info,
    "allowed",
    target="http.server",
    loc=readme_source_loc("fanout-allowed"),
    )
    ctx.event(
    Info,
    "blocked",
    target="db",
    loc=readme_source_loc("fanout-blocked"),
    )
    // The unfiltered lane receives both events.
    debug_inspect(
    left.events,
    content=(
    #|[
    #| {
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "allowed",
    #| target: "http.server",
    #| loc: <SourceLoc: "fanout-allowed">,
    #| },
    #| trace_id: 00000000000000000000000000000001,
    #| span: None,
    #| message: None,
    #| fields: [],
    #| },
    #| {
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "blocked",
    #| target: "db",
    #| loc: <SourceLoc: "fanout-blocked">,
    #| },
    #| trace_id: 00000000000000000000000000000001,
    #| span: None,
    #| message: None,
    #| fields: [],
    #| },
    #|]
    ),
    )
    // The filtered lane sees the event that matched its target filter.
    debug_inspect(
    right.events,
    content=(
    #|[
    #| {
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "allowed",
    #| target: "http.server",
    #| loc: <SourceLoc: "fanout-allowed">,
    #| },
    #| trace_id: 00000000000000000000000000000001,
    #| span: None,
    #| message: None,
    #| fields: [],
    #| },
    #|]
    ),
    )
    }

    #Async Propagation

    When one async flow branches into multiple tasks, the parent task has to choose how the new task should relate to the current trace.

    • spawn_inherit: keep exactly the same context and current span
    • spawn_child_span: create a new child span under the current span
    • spawn_follower_span: create a new span with a follows-from link that records a causal relationship

    Choose the helper that matches the relationship the trace should express. In MoonBit, these helpers model single-threaded async task relationships and handoff.

    • Use spawn_inherit when the new task is part of the same logical operation. A separate span would add noise. Typical cases are splitting one step into helper tasks, breaking a request flow into smaller async pieces, or moving small bookkeeping work onto another task. Events from the inherited task appear under the current span. The inherited task has no separate duration, status, or fields.
    • Use spawn_child_span when the new task is a real sub-step that should be timed and described independently. This is the usual choice for branched async work such as querying a shard, calling another service, processing one item in a batch, or running a retryable async step. The child span keeps the structure clear: the parent started this work and conceptually owns it.
    • Use spawn_follower_span when the current span caused the work and the new task should appear as a related handoff. Typical cases are enqueueing a job for later execution, triggering a webhook, handing work off to another pipeline, or starting deferred async work that may outlive the parent span. The follower stays in the same trace for log correlation. The trace records the relationship as a causal link.

    A practical rule of thumb:

    • Parent continues the same operation: use spawn_inherit
    • Parent starts a sub-step with nested timing: use spawn_child_span
    • Parent triggers or hands off work: use spawn_follower_span

    ///|
    async test "spawn helpers preserve explicit relationships" {
    let capture = ReadmeCapture::new()
    let ctx = readme_root_ctx(@tracing.Dispatch::from_subscriber(capture))

    // All three helpers stay in the same trace. They express three
    // relationships to the current span: reuse it, create a child, or create a
    // follower linked by causality.
    ctx.with_span(
    Info,
    "parent",
    parent_ctx => {
    let parent = parent_ctx.current_span().unwrap()
    @async.with_task_group(group => {
    let inherited_task : @async.Task[@tracing.SpanContext?] = @tracing.spawn_inherit(
    group,
    parent_ctx,
    inherited_ctx => {
    inherited_ctx.event(
    Info,
    "inside_inherit",
    target="readme.async",
    loc=readme_source_loc("inside-inherit"),
    )
    inherited_ctx.current_span()
    },
    )
    let child_task : @async.Task[@tracing.SpanContext] = @tracing.spawn_child_span(
    group,
    parent_ctx,
    Info,
    "child",
    target="readme.async",
    loc=readme_source_loc("child"),
    child_ctx => child_ctx.current_span().unwrap(),
    )
    let follower_task : @async.Task[@tracing.SpanContext] = @tracing.spawn_follower_span(
    group,
    parent_ctx,
    Info,
    "follower",
    target="readme.async",
    loc=readme_source_loc("follower"),
    follower_ctx => follower_ctx.current_span().unwrap(),
    )

    // `spawn_inherit` reuses the exact current span. The other two helpers
    // create distinct spans with different `SpanContext` values.
    assert_true(inherited_task.wait() == Some(parent))
    assert_true(child_task.wait() != parent)
    assert_true(follower_task.wait() != parent)
    })
    },
    target="readme.async",
    loc=readme_source_loc("parent"),
    )

    // This is the original span created in the parent task.
    debug_inspect(
    capture.start_named("parent"),
    content=(
    #|{
    #| metadata: {
    #| kind: Span,
    #| level: Info,
    #| name: "parent",
    #| target: "readme.async",
    #| loc: <SourceLoc: "parent">,
    #| },
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| parent: None,
    #| fields: [],
    #|}
    ),
    )
    // A child span keeps the trace id and records the parent edge explicitly.
    debug_inspect(
    capture.start_named("child"),
    content=(
    #|{
    #| metadata: {
    #| kind: Span,
    #| level: Info,
    #| name: "child",
    #| target: "readme.async",
    #| loc: <SourceLoc: "child">,
    #| },
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000002,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| parent: Some(
    #| {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| ),
    #| fields: [],
    #|}
    ),
    )
    // A follower span stays in the same trace and leaves the parent field empty.
    // A later `SpanLink` records the causal relationship.
    debug_inspect(
    capture.start_named("follower"),
    content=(
    #|{
    #| metadata: {
    #| kind: Span,
    #| level: Info,
    #| name: "follower",
    #| target: "readme.async",
    #| loc: <SourceLoc: "follower">,
    #| },
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000003,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| parent: None,
    #| fields: [],
    #|}
    ),
    )
    // The inherited task emits inside the parent's span.
    debug_inspect(
    capture.events[0],
    content=(
    #|{
    #| metadata: {
    #| kind: Event,
    #| level: Info,
    #| name: "inside_inherit",
    #| target: "readme.async",
    #| loc: <SourceLoc: "inside-inherit">,
    #| },
    #| trace_id: 00000000000000000000000000000001,
    #| span: Some(
    #| {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| ),
    #| message: None,
    #| fields: [],
    #|}
    ),
    )
    // The follower relationship is recorded as a link.
    debug_inspect(
    capture.links[0],
    content=(
    #|{
    #| span: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000003,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #| follows_from: {
    #| trace_id: 00000000000000000000000000000001,
    #| span_id: 0000000000000001,
    #| trace_flags: { raw: 1 },
    #| trace_state: { entries: [] },
    #| is_remote: false,
    #| },
    #|}
    ),
    )
    }

    #Building a Custom Backend

    A backend is just a Subscriber implementation plus a Dispatch built from it. The ReadmeCapture helper earlier in this document is already a complete in-memory backend for tests.

    For production code, the minimal pattern is:

    1. implement Subscriber
    2. build a dispatch with Dispatch::from_subscriber
    3. create a root context with TraceContext::root
    4. pass that context explicitly through your program

    The records delivered to a subscriber are:

    • SpanStart
    • SpanRecord
    • EventRecord
    • SpanEnd
    • SpanLink

    #JSON Lines Package

    moonbit-community/tracing/jsonl is the ready-made backend in this repository.

    Use it when you want:

    • newline-delimited JSON output
    • a dedicated async writer task with bounded queues
    • with_json_stdout or with_json_stderr for quick setup on native targets
    • direct runtime control through JsonRuntime when you need flush, shutdown, or stats

    The main public entry points are:

    • with_json_writer(writer, options, f)
    • with_json_stdout(options, f)
    • with_json_stderr(options, f)
    • JsonRuntime::start_in(group, writer, options)
    • JsonRuntime::flush()
    • JsonRuntime::shutdown()
    • JsonRuntime::stats()

    JsonRuntime::stats().unclosed_spans is a live snapshot of spans started through the runtime dispatch with open handles.

    #logfmt Package

    moonbit-community/tracing/logfmt is the human-readable backend in this repository.

    Use it when you want:

    • logfmt output with stable key ordering
    • one line per tracing record
    • a dedicated async writer task with bounded queues
    • with_logfmt_stdout or with_logfmt_stderr for quick setup on native targets
    • direct runtime control through LogfmtRuntime when you need flush, shutdown, or stats

    The main public entry points are:

    • with_logfmt_writer(writer, options, f)
    • with_logfmt_stdout(options, f)
    • with_logfmt_stderr(options, f)
    • LogfmtRuntime::start_in(group, writer, options)
    • LogfmtRuntime::flush()
    • LogfmtRuntime::shutdown()
    • LogfmtRuntime::stats()

    LogfmtRuntime::stats().unclosed_spans is a live snapshot of spans started through the runtime dispatch with open handles.

    #OpenTelemetry Package

    moonbit-community/tracing/opentelemetry adds W3C propagation and a generic batch export runtime.

    Use it when you want:

    • parse and inject traceparent, validated tracestate, and strictly decoded UTF-8 baggage
    • root a local trace under a valid propagated remote parent
    • export ReadableSpan batches into your own backend
    • attach OpenTelemetry-specific span overrides such as name, kind, and status

    The main public entry points are:

    • W3cPropagator, TraceContextPropagator, BaggagePropagator
    • IncomingContext::root
    • with_exporter(exporter, options, f)
    • OpenTelemetryRuntime::start_in(group, exporter, options)
    • OpenTelemetryRuntime::flush()
    • OpenTelemetryRuntime::shutdown()
    • OpenTelemetryRuntime::stats()
    • Resource, InstrumentationScope, ReadableSpan
    • otel_name, otel_kind, otel_status_code, otel_status_description

    #API Summary

    Core package:

    • TraceContext
    • SpanHandle
    • Dispatch
    • TraceIdAllocator
    • TraceId, SpanId, SpanContext
    • TraceFlags, TraceState, Baggage
    • Metadata, SpanStart, SpanRecord, EventRecord, SpanEnd, SpanLink
    • Level, SpanStatus, Filter
    • Value, Field, IntoValue
    • field
    • spawn_inherit, spawn_child_span, spawn_follower_span

    JSON Lines package:

    • JsonOptions
    • JsonRuntime
    • JsonStats
    • JsonRuntimeError
    • with_json_writer, with_json_stdout, with_json_stderr

    logfmt package:

    • LogfmtOptions
    • LogfmtRuntime
    • LogfmtStats
    • LogfmtRuntimeError
    • with_logfmt_writer, with_logfmt_stdout, with_logfmt_stderr

    OpenTelemetry package:

    • IncomingContext
    • TraceContextPropagator, BaggagePropagator, W3cPropagator
    • OpenTelemetryOptions
    • OpenTelemetryRuntime
    • OpenTelemetryStats
    • OpenTelemetryRuntimeError
    • Resource, InstrumentationScope, ReadableSpan, ReadableEvent, ReadableLink
    • SpanKind, StatusCode, Status
    • with_exporter

    #Validation

    The checked examples in this README are intended to stay in sync with the code. After editing the repository, the expected validation flow is:

    moon check

    moon test --target native

    IntoValue

    pub(open) trait IntoValue {
    fn into_value(Self) -> Value
    }

    Conversion trait used by field and other convenience APIs.
    impl IntoValue for Bool
    impl IntoValue for Int
    impl IntoValue for Int64
    impl IntoValue for UInt
    impl IntoValue for UInt64
    impl IntoValue for Double
    impl IntoValue for String
    impl IntoValue for Bytes

    Subscriber

    pub(open) trait Subscriber {
    fn on_span_start(Self, SpanStart) -> Unit
    fn on_span_record(Self, SpanRecord) -> Unit = _
    fn on_event(Self, EventRecord) -> Unit
    fn on_span_end(Self, SpanEnd) -> Unit
    fn on_span_link(Self, SpanLink) -> Unit = _
    }

    Subscriber implementations receive the records produced by enabled tracing callsites.

    Filtering is decided by Dispatch, not by individual subscribers.

    Baggage

    pub struct Baggage {
    // private fields
    } derive(Compare, Eq, Hash,
    Debug
    )

    Ordered baggage members carried by a trace context.
    impl Default for Baggage

    Baggage::empty

    fn Baggage::empty() -> Baggage

    Baggage::entries

    fn Baggage::entries(self : Baggage) -> Array[BaggageEntry]

    Baggage::from_header

    fn Baggage::from_header(header : StringView) -> Baggage?

    Baggage::get

    fn Baggage::get(self : Baggage, name : StringView) -> BaggageEntry?

    Baggage::header

    fn Baggage::header(self : Baggage) -> String

    Baggage::insert

    fn Baggage::insert(self : Baggage, name : String, value : String, metadata? : String) -> Baggage?

    Baggage::is_empty

    fn Baggage::is_empty(self : Baggage) -> Bool

    Baggage::remove

    fn Baggage::remove(self : Baggage, name : StringView) -> Baggage

    BaggageEntry

    pub struct BaggageEntry {
    name : String
    value : String
    metadata : String?
    } derive(Compare, Eq, Hash,
    Debug
    )

    A single W3C baggage member.

    Dispatch

    pub struct Dispatch {
    // private fields
    }

    Dispatch is the filtering and fanout authority for tracing records.

    Dispatch::fanout

    fn Dispatch::fanout(dispatches : ArrayView[Dispatch]) -> Dispatch

    Combine multiple dispatches into a single fanout dispatch.

    Dispatch::filtered

    fn Dispatch::filtered(self : Dispatch, filter : Filter) -> Dispatch

    Return a dispatch that additionally applies filter to every existing lane.

    Dispatch::from_subscriber

    fn Dispatch::from_subscriber(subscriber : &Subscriber) -> Dispatch

    Create a dispatch with a single unfiltered subscriber lane.

    Dispatch::noop

    fn Dispatch::noop() -> Dispatch

    Create a dispatch that never enables any event or span.

    EventRecord

    pub struct EventRecord {
    metadata : Metadata
    trace_id : TraceId
    span : SpanContext?
    message : String?
    fields : Array[Field]
    } derive(
    Debug
    )

    Record emitted for standalone events.

    Field

    pub struct Field {
    name : String
    value : Value
    } derive(Eq, Hash,
    Debug
    )

    A named structured field attached to a span or event.

    Filter

    pub(all) enum Filter {
    LevelFilter(Level)
    TargetFilter(Map[String, Level])
    AndFilter(Filter, Filter)
    } derive(
    Debug
    )

    Metadata-only filter expression used by Dispatch.

    Level

    pub(all) enum Level {
    Trace
    Debug
    Info
    Warn
    Error
    } derive(Compare, Eq, Hash,
    Debug
    )

    Severity levels understood by the tracing core.

    The ordering is from most verbose to least verbose. A LevelFilter(Info) therefore enables Info, Warn, and Error, while filtering out Debug and Trace.

    Metadata

    pub struct Metadata {
    kind : RecordKind
    level : Level
    name : String
    target : String
    loc : SourceLoc
    } derive(
    Debug
    )

    Static metadata attached to a tracing callsite.

    target is either supplied explicitly by the caller or derived from SourceLoc using the documented ...@package/path suffix rule.

    RecordKind

    pub(all) enum RecordKind {
    Span
    Event
    } derive(Compare, Eq, Hash,
    Debug
    )

    Distinguishes metadata for span-producing callsites from event-producing callsites.

    SpanContext

    #alias(SpanRef)
    pub struct SpanContext {
    trace_id : TraceId
    span_id : SpanId
    trace_flags : TraceFlags
    trace_state : TraceState
    is_remote : Bool
    } derive(Compare, Eq, Hash,
    Debug
    )

    Immutable span identity used for parenting, linking, and propagation.

    SpanContext is safe to copy and pass across tasks because it does not own span lifecycle operations.

    trace_flags, trace_state, and is_remote make the value sufficient for W3C propagation and OpenTelemetry linking.

    SpanContext::invalid

    fn SpanContext::invalid() -> SpanContext

    SpanContext::is_valid

    fn SpanContext::is_valid(self : SpanContext) -> Bool

    SpanContext::new

    fn SpanContext::new(trace_id : TraceId, span_id : SpanId, trace_flags? : TraceFlags, trace_state? : TraceState, is_remote? : Bool) -> SpanContext

    SpanEnd

    pub struct SpanEnd {
    span : SpanContext
    status : SpanStatus
    error : String?
    } derive(
    Debug
    )

    Record emitted when a span ends.

    SpanHandle

    pub struct SpanHandle {
    // private fields
    }

    Handle that owns the lifecycle of a started span.

    A disabled handle represents a span callsite that was filtered out. Disabled handles never emit records and all lifecycle methods report false.

    SpanHandle::close

    fn SpanHandle::close(self : SpanHandle, status? : SpanStatus, error? : String) -> Bool

    Close a span handle exactly once.

    status defaults to Ok. When error is provided it is carried in the emitted SpanEnd record.

    The function returns true only for the first successful close.

    SpanHandle::follows_from

    fn SpanHandle::follows_from(self : SpanHandle, cause : SpanContext) -> Bool

    Emit a follows-from link from this span to cause.

    The function returns false when the handle is disabled or the span was already closed.

    SpanHandle::record

    fn SpanHandle::record(self : SpanHandle, fields : ArrayView[Field]) -> Bool

    Record additional fields on an active span.

    The function returns false when the handle is disabled or the span was already closed.

    SpanHandle::span_context

    fn SpanHandle::span_context(self : SpanHandle) -> SpanContext?

    Return the span identity owned by this handle.

    Disabled handles return None.

    SpanHandle::span_ref

    fn SpanHandle::span_ref(self : SpanHandle) -> SpanContext?

    SpanId

    pub struct SpanId {
    // private fields
    } derive(Compare, Eq, Hash)

    Identifier for a single span within a trace.
    impl Show for SpanId

    SpanId::from_bytes

    fn SpanId::from_bytes(bytes : BytesView) -> SpanId?

    SpanId::from_hex

    fn SpanId::from_hex(hex : StringView) -> SpanId?

    SpanId::to_bytes

    fn SpanId::to_bytes(self : SpanId) -> Bytes

    SpanId::to_hex

    fn SpanId::to_hex(self : SpanId) -> String

    pub struct SpanLink {
    span : SpanContext
    follows_from : SpanContext
    } derive(
    Debug
    )

    Record emitted for follows-from relationships.

    SpanRecord

    pub struct SpanRecord {
    span : SpanContext
    fields : Array[Field]
    } derive(
    Debug
    )

    Record emitted when an existing span receives additional fields.

    SpanStart

    pub struct SpanStart {
    metadata : Metadata
    span : SpanContext
    parent : SpanContext?
    fields : Array[Field]
    } derive(
    Debug
    )

    Record emitted when a span starts.

    SpanStatus

    pub(all) enum SpanStatus {
    Ok
    Error
    Cancelled
    } derive(Compare, Eq, Hash,
    Debug
    )

    Completion state emitted when a span ends.

    TraceContext

    pub struct TraceContext {
    // private fields
    }

    Snapshot of tracing state that callers pass explicitly across async boundaries.

    TraceContext::baggage

    fn TraceContext::baggage(self : TraceContext) -> Baggage

    TraceContext::current_span

    fn TraceContext::current_span(self : TraceContext) -> SpanContext?

    Return the current span, if any.

    TraceContext::debug

    #callsite(autofill(loc))
    fn TraceContext::debug(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit

    Emit a Debug level event from the current trace context.

    TraceContext::error

    #callsite(autofill(loc))
    fn TraceContext::error(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit

    Emit an Error level event from the current trace context.

    TraceContext::event

    #callsite(autofill(loc))
    fn TraceContext::event(self : TraceContext, level : Level, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit

    Emit an event from the current trace context.

    If no dispatch lane enables the callsite metadata, the event is ignored.

    TraceContext::info

    #callsite(autofill(loc))
    fn TraceContext::info(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit

    Emit an Info level event from the current trace context.

    TraceContext::propagated_span

    fn TraceContext::propagated_span(self : TraceContext) -> SpanContext?

    Return the span that should be propagated to downstream work.

    This is the current local span when one exists, otherwise the propagated remote parent captured by root_with_parent.

    TraceContext::root

    fn TraceContext::root(dispatch : Dispatch, trace_ids : TraceIdAllocator) -> TraceContext

    Create a root tracing context backed by dispatch.

    The trace identifier is allocated lazily when the context first emits an enabled record.

    TraceContext::root_with_parent

    fn TraceContext::root_with_parent(dispatch : Dispatch, trace_ids : TraceIdAllocator, parent : SpanContext, baggage? : Baggage) -> TraceContext

    Create a root tracing context that inherits a propagated remote parent.

    TraceContext::span

    #callsite(autofill(loc))
    fn TraceContext::span(self : TraceContext, level : Level, name : String, target? : String, fields? : ArrayView[Field], follows_from? : ArrayView[SpanContext], loc~ : SourceLoc) -> (SpanHandle, TraceContext)

    Start a child span below the current span, if the callsite is enabled.

    If the span is filtered out, the returned child context is exactly self and the handle is disabled.

    TraceContext::trace

    #callsite(autofill(loc))
    fn TraceContext::trace(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit

    Emit a Trace level event from the current trace context.

    TraceContext::warn

    #callsite(autofill(loc))
    fn TraceContext::warn(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit

    Emit a Warn level event from the current trace context.

    TraceContext::with_baggage

    fn TraceContext::with_baggage(self : TraceContext, baggage : Baggage) -> TraceContext

    TraceContext::with_span

    #callsite(autofill(loc))
    async fn[X] TraceContext::with_span(self : TraceContext, level : Level, name : String, target? : String, fields? : ArrayView[Field], follows_from? : ArrayView[SpanContext], loc~ : SourceLoc, f : async (TraceContext) -> X) -> X

    Run f inside a child span when the callsite is enabled.

    On normal return an enabled span ends with SpanStatus::Ok. When f is cancelled, an enabled span ends with SpanStatus::Cancelled. Any other error ends an enabled span with SpanStatus::Error, records err.to_string() as the end error text, and then re-raises the original error.

    If the callsite is filtered out, f runs with the original context and no span records are emitted.

    TraceFlags

    pub struct TraceFlags {
    // private fields
    } derive(Compare, Eq, Hash,
    Debug
    )

    Trace flags carried by W3C traceparent.

    TraceFlags::is_sampled

    fn TraceFlags::is_sampled(self : TraceFlags) -> Bool

    TraceFlags::new

    fn TraceFlags::new(raw : UInt) -> TraceFlags

    TraceFlags::not_sampled

    fn TraceFlags::not_sampled() -> TraceFlags

    TraceFlags::sampled

    fn TraceFlags::sampled() -> TraceFlags

    TraceFlags::to_uint

    fn TraceFlags::to_uint(self : TraceFlags) -> UInt

    TraceId

    pub struct TraceId {
    // private fields
    } derive(Compare, Eq, Hash)

    Identifier for a trace tree.
    impl Show for TraceId

    TraceId::from_bytes

    fn TraceId::from_bytes(bytes : BytesView) -> TraceId?

    TraceId::from_hex

    fn TraceId::from_hex(hex : StringView) -> TraceId?

    TraceId::to_bytes

    fn TraceId::to_bytes(self : TraceId) -> Bytes

    TraceId::to_hex

    fn TraceId::to_hex(self : TraceId) -> String

    TraceIdAllocator

    pub struct TraceIdAllocator {
    // private fields
    }

    TraceIdAllocator::new

    TraceIdAllocator::new_seeded

    fn TraceIdAllocator::new_seeded(seed : UInt64) -> TraceIdAllocator

    Construct a deterministic allocator for tests and documentation.

    seed controls the first lazily allocated trace id. It must leave room for the allocator's first increment. For example, new_seeded(0) reproduces the historical sequence that starts from ...01.

    TraceState

    pub struct TraceState {
    // private fields
    } derive(Compare, Eq, Hash,
    Debug
    )

    Ordered W3C tracestate members carried alongside the current trace.

    TraceState::empty

    fn TraceState::empty() -> TraceState

    TraceState::entries

    fn TraceState::entries(self : TraceState) -> Array[(String, String)]

    TraceState::from_header

    fn TraceState::from_header(header : StringView) -> TraceState?

    TraceState::get

    fn TraceState::get(self : TraceState, key : StringView) -> String?

    TraceState::header

    fn TraceState::header(self : TraceState) -> String

    TraceState::insert

    fn TraceState::insert(self : TraceState, key : String, value : String) -> TraceState?

    TraceState::is_empty

    fn TraceState::is_empty(self : TraceState) -> Bool

    TraceState::remove

    fn TraceState::remove(self : TraceState, key : StringView) -> TraceState

    Value

    pub(all) enum Value {
    Null
    Bool(Bool)
    Int(Int)
    Int64(Int64)
    UInt(UInt)
    UInt64(UInt64)
    Double(Double)
    String(String)
    Bytes(Bytes)
    Array(Array[Value])
    Object(Array[(String, Value)])
    } derive(Eq, Hash)

    Structured field values carried by spans and events.

    Object preserves insertion order. This is important for logging pipelines that rely on stable field ordering. Object field names must be unique within each object value.

    Bytes values are encoded by the formatter as base64 text.
    impl IntoValue for Value

    Value::to_json_string

    fn Value::to_json_string(self : Value) -> String

    Encode a tracing value into JSON text without converting through the core Json AST.

    field

    fn[T : IntoValue] field(name : String, value : T) -> Field

    Create a structured field by converting value into a tracing Value.

    spawn_child_span

    #callsite(autofill(loc))
    fn[G, X] spawn_child_span(group :
    TaskGroup
    [G], ctx : TraceContext, level : Level, name : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc, f : async (TraceContext) -> X, no_wait? : Bool, allow_failure? : Bool) ->
    Task
    [X]

    Spawn a task inside a new child span in ctx's trace.

    The new span is a child of ctx.current_span() when one exists. Otherwise it falls back to the propagated root parent, if any.

    spawn_follower_span

    #callsite(autofill(loc))
    fn[G, X] spawn_follower_span(group :
    TaskGroup
    [G], ctx : TraceContext, level : Level, name : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc, f : async (TraceContext) -> X, no_wait? : Bool, allow_failure? : Bool) ->
    Task
    [X]

    Spawn a task in a new span that stays in the same trace but is not a tree child of the current span.

    When ctx.current_span() exists, the new span emits a single follows-from link to it. When there is no current span, the spawned task still stays in the same trace and no link is emitted.

    spawn_inherit

    fn[G, X] spawn_inherit(group :
    TaskGroup
    [G], ctx : TraceContext, f : async (TraceContext) -> X, no_wait? : Bool, allow_failure? : Bool) ->
    Task
    [X]

    Spawn a task that inherits the exact tracing context ctx.