Last active
May 26, 2025 15:36
-
-
Save lmmx/61a2d5a7ea735b251dadb7e193248de1 to your computer and use it in GitHub Desktop.
Demo of the tracing crate to automatically trace function entry and exit (each function must have the `#[instrument]` attribute)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env rust-script | |
//! Automatic function call tracing with parameters | |
//! | |
//! ```cargo | |
//! [dependencies] | |
//! tracing = "0.1" | |
//! tracing-subscriber = { version = "0.3", features = ["fmt"] } | |
//! ``` | |
use tracing::instrument; | |
// Use #[instrument(level = "info")] to ensure visibility | |
// and add ret to automatically log return values | |
#[instrument(level = "info", ret)] | |
fn baz(value: i32, name: &str) -> i32 { | |
let result = value * 2; | |
if name == "special" { | |
result + 100 | |
} else { | |
result | |
} | |
} | |
#[instrument(level = "info", ret)] | |
fn bar(input: i32, multiplier: f64) -> i32 { | |
let adjusted = (input as f64 * multiplier) as i32; | |
let result1 = baz(adjusted, "normal"); | |
let result2 = baz(adjusted + 5, "special"); | |
result1 + result2 | |
} | |
#[instrument(level = "info", ret)] | |
fn foo(start_value: i32) -> i32 { | |
bar(start_value, 1.5) | |
} | |
fn main() { | |
// Configure tracing to show entry/exit events | |
tracing_subscriber::fmt() | |
.with_max_level(tracing::Level::INFO) | |
.with_target(false) | |
.with_span_events(tracing_subscriber::fmt::format::FmtSpan::ENTER | tracing_subscriber::fmt::format::FmtSpan::EXIT) | |
.init(); | |
println!("=== Starting traced execution ==="); | |
let result = foo(42); | |
println!("Final result: {}\n", result); | |
println!("=== Another call ==="); | |
let result2 = foo(10); | |
println!("Second result: {}", result2); | |
} |
Author
lmmx
commented
May 26, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment