How to know who (which function) called a function without using RUST_BACKTRACE

Hi Friends,

Is there any way in Rust to know that who (Which Function) called a function in a programmatic way without using RUST_BACKTRACE?

There's no general, portable way to do this.

There's an unstable #[track_caller] attribute which enables this, but it's quite new and only usable on nightly.

There's also the std::module_path!() and std::line!() if you want to get the module path or line of wherever the macro is evaluated. That's the mechanism used by the log crate to embed the file name and line number in logs.

Are you able to give us more information on what you're trying to accomplish? There may be a better way that doesn't require walking backtraces.

1 Like

I am not looking the solution for any specific scenario, instead I am looking for a solution which can be useful while day-to-day programming. So that whenever I want to know that who all are calling any function foo on any event, then I get the output in the terminal while the program in running and not by compulsory panic! call and using RUST_BACKTRACE flag.

I am looking for a line as simple as println! or something like a macro attribute on a function that is able to tell that who is calling that specific function when any event is triggered at runtime.

I found this crate which allows to programmatically obtain the same thing what I discussed above by just placing following lines inside any function:

let bt = Backtrace::new();
println!("{:?}", bt);