CodeSampleX

示例

tracing-attributes 0.1.31: tracing_attributes::instrument

已验证示例 — cargo tracing-attributes 0.1.31: tracing_attributes::instrument. contract 在 rust 1 · linux alpine/x64 · docker 上运行并通过.

sha256:02ee79cfdc32496de80760fe95e0908be9e5d729c779bcb6b8f311032c06629c

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux · alpine · musl x64 cargo

验证运行环境

环境 契约 阶段 运行日期
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-01

案例

HOW
目标
verify tracing_attributes::instrument in pkg:cargo/tracing-attributes@0.1.31
包
符号
  • tracing_attributes::instrument
创建时间
2026-11-01T22:53:14Z

契约

  1. #[tracing_attributes::instrument] creates and enters a span with custom name, target, and level around a function invocation
  2. skip(secret) excludes the skipped argument from recorded span fields while recording remaining arguments
  3. fields(order_id = id, tag = "priority") attaches custom evaluated and literal fields to the span
  4. ret emits an event on function return containing the return field with the Debug-formatted return value

文件

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

下载源代码构件 (tar.gz)

源代码

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 = "sample-tracing-attributes"
version = "0.1.0"
dependencies = [
 "tracing",
 "tracing-attributes",
]

[[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-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 = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
Cargo.toml
[package]
name = "sample-tracing-attributes"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
tracing = { version = "=0.1.41", default-features = false, features = ["std"] }
tracing-attributes = "=0.1.31"

[[bin]]
name = "contract"
path = "test/contract.rs"
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 tracing_attributes::instrument in pkg:cargo/tracing-attributes@0.1.31
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/tracing-attributes@0.1.31
Demonstrate these symbols/APIs:
  - tracing_attributes::instrument

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:759ddbc1fd5bcce46ce9bf328eefc7bd4a68219d3158cf327c7fac89e112bc00","contract":["#[tracing_attributes::instrument] creates and enters a span with custom name, target, and level around a function invocation","skip(secret) excludes the skipped argument from recorded span fields while recording remaining arguments","fields(order_id = id, tag = \"priority\") attaches custom evaluated and literal fields to the span","ret emits an event on function return containing the return field with the Debug-formatted return value"],"goal":"verify tracing_attributes::instrument in pkg:cargo/tracing-attributes@0.1.31","kind":"HOW","packages":["pkg:cargo/tracing-attributes@0.1.31"],"schemaVersion":1,"symbols":["tracing_attributes::instrument"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/tracing-attributes@0.1.31"],"schemaVersion":1,"subject":"pkg:cargo/tracing-attributes@0.1.31","symbols":["tracing_attributes::instrument"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tracing_attributes::instrument in pkg:cargo/tracing-attributes@0.1.31",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/tracing-attributes@0.1.31"
  ],
  "symbols": [
    "tracing_attributes::instrument"
  ]
}
src/lib.rs
//! Clean-room verification sample for tracing_attributes::instrument.

pub use tracing_attributes::instrument;
test/contract.rs
use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Metadata, Subscriber};
use tracing_attributes::instrument;

#[derive(Clone)]
struct RecordedSpan {
    name: String,
    target: String,
    level: tracing::Level,
    fields: Vec<(String, String)>,
    entered: u32,
    exited: u32,
}

#[derive(Clone)]
struct RecordedEvent {
    level: tracing::Level,
    fields: Vec<(String, String)>,
}

#[derive(Default)]
struct FieldCollector {
    fields: Vec<(String, String)>,
}

impl Visit for FieldCollector {
    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
        self.fields
            .push((field.name().to_string(), format!("{:?}", value)));
    }
}

struct TestSubscriber {
    spans: Arc<Mutex<Vec<RecordedSpan>>>,
    events: Arc<Mutex<Vec<RecordedEvent>>>,
}

impl Subscriber for TestSubscriber {
    fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
        true
    }

    fn new_span(&self, span: &Attributes<'_>) -> Id {
        let mut collector = FieldCollector::default();
        span.record(&mut collector);
        let mut spans = self.spans.lock().unwrap();
        let id = Id::from_u64((spans.len() + 1) as u64);
        spans.push(RecordedSpan {
            name: span.metadata().name().to_string(),
            target: span.metadata().target().to_string(),
            level: *span.metadata().level(),
            fields: collector.fields,
            entered: 0,
            exited: 0,
        });
        id
    }

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

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

    fn event(&self, event: &Event<'_>) {
        let mut collector = FieldCollector::default();
        event.record(&mut collector);
        self.events.lock().unwrap().push(RecordedEvent {
            level: *event.metadata().level(),
            fields: collector.fields,
        });
    }

    fn enter(&self, span: &Id) {
        let mut spans = self.spans.lock().unwrap();
        if let Some(entry) = spans.get_mut((span.into_u64() - 1) as usize) {
            entry.entered += 1;
        }
    }

    fn exit(&self, span: &Id) {
        let mut spans = self.spans.lock().unwrap();
        if let Some(entry) = spans.get_mut((span.into_u64() - 1) as usize) {
            entry.exited += 1;
        }
    }
}

#[instrument(
    name = "compute_order",
    target = "billing",
    level = "debug",
    skip(secret),
    fields(order_id = id, tag = "priority"),
    ret
)]
fn process_order(id: u32, secret: &str) -> u32 {
    let _ = secret;
    id * 2
}

fn main() {
    let spans = Arc::new(Mutex::new(Vec::new()));
    let events = Arc::new(Mutex::new(Vec::new()));
    let subscriber = TestSubscriber {
        spans: Arc::clone(&spans),
        events: Arc::clone(&events),
    };

    tracing::subscriber::with_default(subscriber, || {
        let res = process_order(21, "top-secret");
        assert_eq!(res, 42);
    });

    let recorded = spans.lock().unwrap();
    assert_eq!(recorded.len(), 1);
    let span = &recorded[0];
    assert_eq!(span.name, "compute_order");
    assert_eq!(span.target, "billing");
    assert_eq!(span.level, tracing::Level::DEBUG);
    assert_eq!(span.entered, 1);
    assert_eq!(span.exited, 1);

    let field_names: Vec<&str> = span.fields.iter().map(|(k, _)| k.as_str()).collect();
    assert!(field_names.contains(&"id"));
    assert!(!field_names.contains(&"secret"));
    assert!(span
        .fields
        .iter()
        .any(|(k, v)| k == "order_id" && v == "21"));
    assert!(span
        .fields
        .iter()
        .any(|(k, v)| k == "tag" && v == "\"priority\""));

    let recorded_events = events.lock().unwrap();
    assert_eq!(recorded_events.len(), 1);
    assert_eq!(recorded_events[0].level, tracing::Level::DEBUG);
    assert!(recorded_events[0]
        .fields
        .iter()
        .any(|(k, v)| k == "return" && v == "42"));
}

原始种子者

匿名