1

I am new in a large complicated codebase. I would like to follow a request as it is being processed. For this I'd like to have a feature that enables printing each function that is being called without having to add trace functionality everywhere in the codebase (see e.g. crate trace).

Ideally I would like exactly this python solution, but in rust (see SO post):

def tracefunc(frame, event, arg, indent=[0]):
      if event == "call":
          indent[0] += 2
          print("-" * indent[0] + "> call function", frame.f_code.co_name)
      elif event == "return":
          print("<" + "-" * indent[0], "exit function", frame.f_code.co_name)
          indent[0] -= 2
      return tracefunc

import sys
sys.setprofile(tracefunc)

main()   # or whatever kicks off your script

EDIT:
A tool that does this may even be better. See e.g. this solution for C++

3
  • 1
    Have you tried using a debuger? Commented Oct 11, 2022 at 11:34
  • 2
    There's no such functionality in the rust source itself. There is LLVM xray, but afaik there's no support for it. Python is a dynamic language with an interpreter, which makes it possible to intercept function calls at runtime, but in a compiled language like Rust or C, it's not possible after the source code has been compiled.
    – hellow
    Commented Oct 11, 2022 at 11:36
  • "For this I'd like to have a feature that enables printing each function that is being called without having to add trace functionality everywhere in the codebase (see e.g. crate trace)." ah yes magic, I know some myself. You post the thing I was going to answer this question is so meaningless. docs.rs/tracing/latest/tracing
    – Stargateur
    Commented Oct 11, 2022 at 11:39

1 Answer 1

1

You could put a panic!() macro in your code, to get a backtrace. You will also need to set the backtrace option with export RUST_BACKTRACE=1 or export RUST_BACKTRACE=full before you execute your program (cargo run).

A way to get a live trace of a running Rust program is through logging. You might want to try the log crate, in conjunction with the syslog crate. Make use of the macros debug!(), info!(), warn!(), and error!() to log messages. You can use the name of the current function if you wish.

Then configure rsyslog to route the messages from your application to a separate logfile, which you can monitor live with something like tail -f /var/log/<yourapp.log> in a separate terminal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.