home ~ socials ~ projects ~ rss

Get the Location of a Calling Function in Rust

September 2025

Use #[track_caller] and std::panic::Location::caller() to get the file and location of where a funciton was called.

fn main() {
  ping();
  alfa();
}

fn alfa() {
  ping();
}

#[track_caller]
fn ping() {
  let caller = std::panic::Location::caller();
  println!("Caller: {}", caller);
}
Output:
Caller: example.rs:2:3
Caller: example.rs:7:3
end of line
Share link:
https://www.alanwsmith.com/en/32/6s/dg/1p/?get-the-location-of-a-calling-function-in-rust