CodeSampleX

Beispiel

tracing 0.1.41: tracing::Subscriber, tracing::subscriber::with_default, tracing::span!

Verifiziertes Beispiel für cargo tracing 0.1.41: tracing::Subscriber, tracing::subscriber::with_default, tracing::span!. Der Vertrag lief auf rust 1 · linux…

sha256:a75236e8361cba971fd76940ee5a771682e62ee0dc2e7d48d830b36b2e0d07d0

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung rust linux x64 rust rust cargo

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-02

Fall

HOW
Ziel
verify pkg:cargo/tracing@0.1.41
Pakete
Symbole
  • tracing::Subscriber
  • tracing::subscriber::with_default
  • tracing::span!
  • tracing::event!
  • tracing::Span::record
  • tracing::field::Visit
Umgebung
rust
Erstellt
2026-11-02T00:00:45Z

Contract

  1. assert custom Subscriber captures span creation with initial fields and late Span::record updates on tracing::field::Empty
  2. assert entering and dropping a span guard tracks active span hierarchy and invokes try_close on drop
  3. assert structured events inside an active span record typed fields and active span id while filtering events below max Level
  4. assert events emitted after subscriber::with_default returns are not delivered to the scoped subscriber

Dateien

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/main.rs
  • tests/contract.rs

Quellartefakt herunterladen (tar.gz)

Quelltext

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"

[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "tracing"
version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
dependencies = [
 "pin-project-lite",
 "tracing-attributes",
 "tracing-core",
]

[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
 "once_cell",
]

[[package]]
name = "tracing-sample"
version = "0.1.0"
dependencies = [
 "tracing",
]

[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
Cargo.toml
[package]
name = "tracing-sample"
version = "0.1.0"
edition = "2021"

[dependencies]
tracing = "=0.1.41"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:cargo/tracing@0.1.41
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/tracing@0.1.41

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:110008fd03bf4fffa60e6790719c8dd829811b9ec749a53527944c0c78150ee9","contract":["assert custom Subscriber captures span creation with initial fields and late Span::record updates on tracing::field::Empty","assert entering and dropping a span guard tracks active span hierarchy and invokes try_close on drop","assert structured events inside an active span record typed fields and active span id while filtering events below max Level","assert events emitted after subscriber::with_default returns are not delivered to the scoped subscriber"],"goal":"verify pkg:cargo/tracing@0.1.41","kind":"HOW","packages":["pkg:cargo/tracing@0.1.41"],"schemaVersion":1,"symbols":["tracing::Subscriber","tracing::subscriber::with_default","tracing::span!","tracing::event!","tracing::Span::record","tracing::field::Visit"]},"contractCommand":["cargo","test","--locked","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/tracing@0.1.41"],"schemaVersion":1,"subject":"pkg:cargo/tracing@0.1.41","symbols":["tracing::Subscriber","tracing::subscriber::with_default","tracing::span!","tracing::event!","tracing::Span::record","tracing::field::Visit"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/tracing@0.1.41",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/tracing@0.1.41"
  ]
}
src/main.rs
use std::collections::BTreeMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Level, Metadata, Subscriber};

#[derive(Debug, Default)]
struct RecordedState {
    spans: BTreeMap<u64, SpanRecord>,
    events: Vec<EventRecord>,
    current_stack: Vec<u64>,
    closed_spans: Vec<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SpanRecord {
    name: &'static str,
    target: &'static str,
    level: Level,
    fields: BTreeMap<String, String>,
    enter_count: usize,
    exit_count: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct EventRecord {
    target: &'static str,
    level: Level,
    fields: BTreeMap<String, String>,
    active_span_id: Option<u64>,
}

struct FieldCollector<'a>(&'a mut BTreeMap<String, String>);

impl Visit for FieldCollector<'_> {
    fn record_str(&mut self, field: &Field, value: &str) {
        self.0.insert(field.name().to_string(), value.to_string());
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        self.0.insert(field.name().to_string(), value.to_string());
    }

    fn record_i64(&mut self, field: &Field, value: i64) {
        self.0.insert(field.name().to_string(), value.to_string());
    }

    fn record_bool(&mut self, field: &Field, value: bool) {
        self.0.insert(field.name().to_string(), value.to_string());
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        self.0.insert(field.name().to_string(), format!("{value:?}"));
    }
}

struct MemorySubscriber {
    next_id: AtomicU64,
    max_level: Level,
    state: Arc<Mutex<RecordedState>>,
}

impl MemorySubscriber {
    fn new(max_level: Level, state: Arc<Mutex<RecordedState>>) -> Self {
        Self {
            next_id: AtomicU64::new(1),
            max_level,
            state,
        }
    }
}

impl Subscriber for MemorySubscriber {
    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
        metadata.level() <= &self.max_level
    }

    fn new_span(&self, span: &Attributes<'_>) -> Id {
        let raw_id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let metadata = span.metadata();
        let mut fields = BTreeMap::new();
        span.record(&mut FieldCollector(&mut fields));

        let mut state = self.state.lock().unwrap();
        state.spans.insert(
            raw_id,
            SpanRecord {
                name: metadata.name(),
                target: metadata.target(),
                level: *metadata.level(),
                fields,
                enter_count: 0,
                exit_count: 0,
            },
        );
        Id::from_u64(raw_id)
    }

    fn record(&self, span: &Id, values: &Record<'_>) {
        let mut state = self.state.lock().unwrap();
        if let Some(entry) = state.spans.get_mut(&span.into_u64()) {
            values.record(&mut FieldCollector(&mut entry.fields));
        }
    }

    fn record_follows_from(&self, _span: &Id, _follows: &Id) {}

    fn event(&self, event: &Event<'_>) {
        let metadata = event.metadata();
        if !self.enabled(metadata) {
            return;
        }
        let mut fields = BTreeMap::new();
        event.record(&mut FieldCollector(&mut fields));

        let mut state = self.state.lock().unwrap();
        let active_span_id = state.current_stack.last().copied();
        state.events.push(EventRecord {
            target: metadata.target(),
            level: *metadata.level(),
            fields,
            active_span_id,
        });
    }

    fn enter(&self, span: &Id) {
        let raw_id = span.into_u64();
        let mut state = self.state.lock().unwrap();
        if let Some(entry) = state.spans.get_mut(&raw_id) {
            entry.enter_count += 1;
        }
        state.current_stack.push(raw_id);
    }

    fn exit(&self, span: &Id) {
        let raw_id = span.into_u64();
        let mut state = self.state.lock().unwrap();
        if let Some(entry) = state.spans.get_mut(&raw_id) {
            entry.exit_count += 1;
        }
        if state.current_stack.last() == Some(&raw_id) {
            state.current_stack.pop();
        }
    }

    fn try_close(&self, id: Id) -> bool {
        let mut state = self.state.lock().unwrap();
        state.closed_spans.push(id.into_u64());
        true
    }
}

fn main() {
    let state = Arc::new(Mutex::new(RecordedState::default()));
    let subscriber = MemorySubscriber::new(Level::INFO, Arc::clone(&state));

    tracing::subscriber::with_default(subscriber, || {
        let span = tracing::span!(
            target: "app::http",
            Level::INFO,
            "handle_request",
            method = "POST",
            status = tracing::field::Empty
        );
        let span_id = span.id().expect("INFO span must be enabled").into_u64();

        {
            let _guard = span.enter();
            tracing::event!(
                target: "app::http",
                Level::INFO,
                bytes = 512_u64,
                authenticated = true,
                "request payload received"
            );
            tracing::event!(
                target: "app::http",
                Level::DEBUG,
                detail = "ignored-debug-event"
            );
            span.record("status", 201_u64);
        }

        drop(span);

        let recorded = state.lock().unwrap();
        assert_eq!(recorded.spans.len(), 1);
        let span_rec = recorded.spans.get(&span_id).expect("span recorded");
        assert_eq!(span_rec.name, "handle_request");
        assert_eq!(span_rec.target, "app::http");
        assert_eq!(span_rec.level, Level::INFO);
        assert_eq!(span_rec.fields.get("method"), Some(&"POST".to_string()));
        assert_eq!(span_rec.fields.get("status"), Some(&"201".to_string()));
        assert_eq!(span_rec.enter_count, 1);
        assert_eq!(span_rec.exit_count, 1);
        assert_eq!(recorded.closed_spans, vec![span_id]);

        assert_eq!(recorded.events.len(), 1);
        let evt = &recorded.events[0];
        assert_eq!(evt.target, "app::http");
        assert_eq!(evt.level, Level::INFO);
        assert_eq!(evt.active_span_id, Some(span_id));
        assert_eq!(evt.fields.get("bytes"), Some(&"512".to_string()));
        assert_eq!(evt.fields.get("authenticated"), Some(&"true".to_string()));
        assert_eq!(
            evt.fields.get("message"),
            Some(&"request payload received".to_string())
        );
    });

    // Events outside `with_default` go to the no-op default subscriber.
    tracing::event!(target: "app::http", Level::ERROR, "outside scope");
    assert_eq!(state.lock().unwrap().events.len(), 1);
}
tests/contract.rs
#[test]
fn contract() {
    let status = std::process::Command::new(env!("CARGO_BIN_EXE_tracing-sample"))
        .status()
        .expect("run tracing-sample binary");
    assert!(status.success());
}

Ursprungs-Seeder

anonym