Structured tracing with explicit context propagation.
///|
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
}///|
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)
}///|
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: [],
#| },
#|]
),
)
}///|
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(_))
}///|
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,
#|}
),
)
}///|
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"),
#| },
#|]
),
)
}///|
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 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,
#| },
#|}
),
)
}moon checkmoon test --target nativepub(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 = _
}pub struct Dispatch {
// private fields
}pub struct Metadata {
kind : RecordKind
level : Level
name : String
target : String
loc : SourceLoc
} derive(Debug)#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)fn SpanContext::new(trace_id : TraceId, span_id : SpanId, trace_flags? : TraceFlags, trace_state? : TraceState, is_remote? : Bool) -> SpanContextpub struct SpanHandle {
// private fields
}pub struct SpanStart {
metadata : Metadata
span : SpanContext
parent : SpanContext?
fields : Array[Field]
} derive(Debug)pub struct TraceContext {
// private fields
}#callsite(autofill(loc))
fn TraceContext::debug(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit#callsite(autofill(loc))
fn TraceContext::error(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit#callsite(autofill(loc))
fn TraceContext::event(self : TraceContext, level : Level, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit#callsite(autofill(loc))
fn TraceContext::info(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unitfn TraceContext::root_with_parent(dispatch : Dispatch, trace_ids : TraceIdAllocator, parent : SpanContext, baggage? : Baggage) -> TraceContext#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)#callsite(autofill(loc))
fn TraceContext::trace(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit#callsite(autofill(loc))
fn TraceContext::warn(self : TraceContext, name : String, message? : String, target? : String, fields? : ArrayView[Field], loc~ : SourceLoc) -> Unit#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) -> Xpub struct TraceIdAllocator {
// private fields
}impl Default for TraceState#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]#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]fn[G, X] spawn_inherit(group : TaskGroup[G], ctx : TraceContext, f : async (TraceContext) -> X, no_wait? : Bool, allow_failure? : Bool) -> Task[X]