Expand description
A procedural macro for tracing the execution of functions.
Adding #[trace]
to the top of any function will insert println!
statements at the beginning
and the end of that function, notifying you of when that function was entered and exited and
printing the argument and return values. This is useful for quickly debugging whether functions
that are supposed to be called are actually called without manually inserting print statements.
Note that this macro requires all arguments to the function and the return value to have types
that implement Debug
. You can disable the printing of certain arguments if necessary.
You can also add #[trace]
to impl
s and mod
s to enable tracing for all functions in the
impl
or mod
. If you use #[trace]
on a mod
or impl
as well as on a method or function
inside one of those elements, then only the outermost #[trace]
is used.
#[trace]
takes a few optional arguments that configure things like the prefixes to use,
enabling/disabling particular arguments or functions, and more. See the
documentation for details.
§Example
See the examples in examples/
. You can run the following example with
cargo run --example example_prefix
.
use trace::trace;
trace::init_depth_var!();
fn main() {
foo(1, 2);
}
#[trace]
fn foo(a: i32, b: i32) {
println!("I'm in foo!");
bar((a, b));
}
#[trace(prefix_enter="[ENTER]", prefix_exit="[EXIT]")]
fn bar((a, b): (i32, i32)) -> i32 {
println!("I'm in bar!");
if a == 1 {
2
} else {
b
}
}
Output:
[+] Entering foo(a = 1, b = 2)
I'm in foo!
[ENTER] Entering bar(a = 1, b = 2)
I'm in bar!
[EXIT] Exiting bar = 2
[-] Exiting foo = ()
Note the convenience trace::init_depth_var!()
macro which declares and
initializes the thread-local DEPTH
variable that is used for indenting the output. Calling
trace::init_depth_var!()
is equivalent to writing:
use std::cell::Cell;
thread_local! {
static DEPTH: Cell<usize> = Cell::new(0);
}
The only time it can be omitted is when #[trace]
is applied to mod
s as it’s defined for you
automatically (see examples/example_mod.rs
). Note that the DEPTH
variable isn’t shared
between mod
s, so indentation won’t be perfect when tracing functions in multiple mod
s. Also
note that using trace as an inner attribute (#![trace]
) is not supported at this time.
Macros§
- init_
depth_ var - A convenience macro for declaring the
DEPTH
variable used for indenting the output
Attribute Macros§
- trace
- Enables tracing the execution of functions